AniUI Academy

Truncate text at a word boundary

easyDOM & Utilities+150 XPPractice

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 inside maxLength.
  • 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.length miscounts emoji and some astral characters. For those, iterate over Array.from(text) instead.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.