Truncate a string at full words
Cut at the last space that fits, then add a suffix.
function truncateWords({ text, max, suffix }) { if (text.length <= max) return text; const cut = text.slice(0, max - suffix.length); const space = cut.lastIndexOf(' '); return `${space > 0 ? cut.slice(0, space) : cut}${suffix}`; }
Input & expected output
Input
{
"text": "Your order 8812 is out for delivery",
"max": 20,
"suffix": "…"
}Expected output
"Your order 8812 is…"The edge case
Input
{
"text": "Supercalifragilistic",
"max": 10,
"suffix": "…"
}Expected output
"Supercali…"Know the limits
- The original truncated strings exactly max long and returned only the suffix when the first word was too long; both are fixed.
- Handy for preview text and notification titles; length is in UTF-16 code units.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Truncate a string at full words from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps strings exactly max long and falls back to a hard cut when the first word is too long; the original returned only the suffix. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.