JavaScript Snippet

Truncate Text with an Ellipsis

Difficulty: Easy

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.

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

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.