TypeScript

Truncate at Word Boundary

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cap a string at `max` characters without splitting a word, appending an ellipsis when truncated. Falls back gracefully if the last word is longer than `max`.
TypeScript
Raw
export function truncateWords(text: string, max: number, ellipsis = '…'): string {
  const t = text.trim();
  if (t.length <= max) return t;
  const budget = max - ellipsis.length;
  if (budget <= 0) return ellipsis.slice(0, max);
  let cut = t.slice(0, budget);
  const lastSpace = cut.lastIndexOf(' ');
  if (lastSpace > budget * 0.5) cut = cut.slice(0, lastSpace);
  return cut.replace(/[\s,.;:]+$/, '') + ellipsis;
}

truncateWords('The quick brown fox jumps over the lazy dog', 20);
// 'The quick brown fox…'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.