Truncate string with ellipsis
| 1 min read
When you need to fit a long title into a tight space and CSS text-overflow: ellipsis isn’t an option (think: button labels, JSON output, table cells with no fixed width), this is the smallest function that does the job.
const truncate = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
truncate("Once upon a time in the West", 10);
// "Once upon …"
truncate("Hi", 10);
// "Hi"
A quick note — use the unicode ellipsis character … (U+2026), not three dots .... It’s one character instead of three, looks tighter typographically, and counts as a single glyph for things like word breaks.
If you care about not slicing mid-word, here’s a slightly longer version:
function truncate(s, n) {
if (s.length <= n) return s;
const sliced = s.slice(0, n);
const lastSpace = sliced.lastIndexOf(" ");
return (lastSpace > 0 ? sliced.slice(0, lastSpace) : sliced) + "…";
}
That’s actually how I do it on this very site for blog excerpts.