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
- GreenSnippets
- MIT
- Executed with Node.js 22
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
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.
Related snippets
- PHP Tested
Truncate multibyte strings safely in PHP
Shorten UTF-8 text with mb_ functions so accents and emoji are never cut in half.
- Python Tested
Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.
- PHP Tested
Slugify a string in PHP
Create URL-safe lowercase slugs from titles, removing accents and punctuation.
- JavaScript Tested
Slugify a string for URLs
Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.

