Truncate a string at full words

Cut at the last space that fits, then add a suffix.

JavaScript Version 1.0.0 · MIT · .md

truncate-a-string-at-full-words.js
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.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.