Skip to content
GreenSnippets

Truncate a string with an ellipsis

Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.

JavaScript
function truncate(text, max, ellipsis = "…") {
  const chars = [...text];
  if (chars.length <= max) return text;
  const room = Math.max(0, max - [...ellipsis].length);
  let cut = chars.slice(0, room).join("");
  const lastSpace = cut.lastIndexOf(" ");
  const endsOnBoundary = chars[room] === " ";
  if (!endsOnBoundary && lastSpace > room * 0.6) cut = cut.slice(0, lastSpace);
  return cut.trimEnd() + ellipsis;
}

Example / expected output

Output
truncate("The quick brown fox jumps over the lazy dog", 20) // "The quick brown fox…"

How it works

Spreading the string ([...text]) iterates code points, so emoji are not split in half. The function backs up to the last space when the cut would split a word and a space exists late enough in the allowed range, then appends the ellipsis; the result never exceeds max characters.