Code Snippets
/

Truncate Text with an Ellipsis

Truncate Text with an Ellipsis

Truncating overflowing text with `...` keeps card layouts and table cells from breaking, but the naive `slice` approach often cuts mid-word or splits a surrogate pair into garbage. This snippet covers the simple character cap, a word-boundary aware version, and a code-point-correct variant for international content. Use it for previews, tooltips, and any space-bounded label.

JavaScript
Easy
3 snippets
strings
utility
code-template

1,154 views

12

function truncate(str, maxLength, suffix = '...') {
    if (typeof str !== 'string') return '';
    if (str.length <= maxLength) return str;
    return str.slice(0, maxLength - suffix.length) + suffix;
}

console.log(truncate('The quick brown fox jumps', 15));
// The quick br...
console.log(truncate('short', 15));
// short
console.log(truncate('exactly fifteen', 15));
// exactly fifteen

The simplest correct truncate keeps the total output (including suffix) within maxLength by slicing at maxLength - suffix.length. Returning the input unchanged when it already fits is the easy branch to forget; without it, a 10-character string gets truncated to '1234567...' even though it could have been displayed in full. This version counts UTF-16 code units, so a string with emoji or rare-script characters can still be cut mid-character. Reach for this when your inputs are ASCII (English UI labels, technical IDs) and you want one defensive line.