AniUI Academy
easy+150 XPPractice

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 "...".

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.