Truncate text at a word boundary
CSS text-overflow: ellipsis only works on one line, so list and card previews are usually truncated in JavaScript. Cutting at a fixed index leaves things like "The quick bro...", which looks broken.
Implement truncate(text, maxLength), where maxLength is at least 4 and counts the three-character ellipsis "...", so the returned string is never longer than maxLength.
If text.length is less than or equal to maxLength, return text unchanged. Otherwise let budget = maxLength - 3 and take head = text.slice(0, budget). If the character at index budget in text is whitespace then head already ends on a word boundary and is kept as it is; otherwise cut head back to everything before its last space, unless head contains no space at all, in which case head is kept as-is so a single very long word is cut mid-word. Finally strip trailing whitespace from head and append "...".
Arguments
textstring- The text to truncate.
maxLengthnumber- The maximum length of the returned string. Must be at least 4, since the ellipsis counts toward it.
Returns
string — The original text when it already fits, otherwise head + "..." cut back to the previous word boundary when possible.
Examples
truncate("Hello world", 20);
// => "Hello world"Short text is returned untouched.
truncate("The quick brown fox jumps", 14);
// => "The quick..."The cut lands inside brown, so head falls back to the previous space.
truncate("Internationalisation", 10);
// => "Interna..."A single long word with no space to fall back to is cut mid-word.
What it has to do
- Return the input unchanged when it is no longer than
maxLength. - Count the three-character
"..."suffix insidemaxLength. - Never split a word, unless the first word alone is longer than the budget.
- Strip trailing whitespace before appending the ellipsis.
Notes
- Checking the character _just past_ the slice is what separates a safe cut from a word-splitting one — if that character is whitespace, the slice already ends on a word boundary and does not need to be shortened.
- This operates on JavaScript's UTF-16 code units, so
text.lengthmiscounts emoji and some astral characters. For those, iterate overArray.from(text)instead.
Stuck? The javascript course covers everything this challenge needs.
- 1.returns short text unchanged
- 2.keeps a whole word when the cut lands on a space
- 3.backs up to the previous space mid word
- 4.cuts a single long word with no space to fall back on
- 5.returns text of exactly maxLength unchanged
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.