Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Truncate text to an exact length with ellipsis in JavaScript

99 Truncate on a word boundary, ellipsis included in the budget

easy

Shorten a description to a maximum total length, ellipsis included, cutting at a space so no word is left half-written and no comma or full stop dangles in front of the dots. Leave anything already short enough completely alone, including a string exactly at the limit. Then handle the one input that has no space to cut at.

Stuck? Three hints, smallest first
  1. 1. Return early when text.length <= max. No ellipsis, no change at all.
  2. 2. The room for real text is max - ellipsis.length. Slice one character past it to find out whether you landed mid-word.
  3. 3. Trim trailing spaces and punctuation off the cut before adding the dots.

The answer

function truncate(text, max, ellipsis = '\u2026') {
  if (text.length <= max) return text;
  const room = max - ellipsis.length;
  const oneOver = text.slice(0, room + 1);
  const lastSpace = oneOver.lastIndexOf(' ');
  const kept = lastSpace > 0 ? oneOver.slice(0, lastSpace) : oneOver.slice(0, room);
  return kept.replace(/[\s,.;:!?-]+$/, '') + ellipsis;
}

const blurb = 'Fresh gari from Ibadan, delivered across Lagos within 24 hours.';

const shortEnough = truncate('Gari, 5kg', 20);
const exactlyAtTheLimit = truncate('Gari, 5kg', 9);
const cut = truncate(blurb, 30);
const cutShorter = truncate(blurb, 20);
const noDanglingStop = truncate('Delivered in Lagos. Ibadan next.', 22);
const oneLongWord = truncate('Ikejaaaaaaaaaaaaaaaaaaaaaaa', 12);
const everyLengthWithinBudget = [shortEnough, exactlyAtTheLimit, cut, cutShorter, noDanglingStop, oneLongWord].map((s) => s.length);

console.log('short enough :', shortEnough);
console.log('cut to 30    :', cut, '(' + cut.length + ')');
console.log('cut to 20    :', cutShorter);
console.log('no space     :', oneLongWord);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('text shorter than the limit comes back untouched, with no dots added', shortEnough, 'Gari, 5kg');
test('text exactly at the limit is untouched too, so the boundary is inclusive', exactlyAtTheLimit, 'Gari, 5kg');
test('a long string is cut at a space, never in the middle of a word', cut, 'Fresh gari from Ibadan\u2026');
test('and a tighter budget simply drops another word', cutShorter, 'Fresh gari from\u2026');
test('trailing punctuation is trimmed off before the ellipsis', noDanglingStop, 'Delivered in Lagos\u2026');
test('a single word with no space in it has to be cut mid-word', oneLongWord, 'Ikejaaaaaaa\u2026');
test('and nothing ever comes back longer than the budget it was given', everyLengthWithinBudget, [9, 9, 23, 16, 19, 12]);

Counting the ellipsis inside the budget is the part that is usually got wrong. slice(0, max) + '…' returns max + 1 characters, which in a fixed-width table or a meta description is exactly the overflow you were truncating to avoid. Subtract the ellipsis first, and the last assertion holds by construction.

Slicing one character past the room is the trick for finding the boundary. If that extra character is a space, the cut at room was already clean; if it is a letter, lastIndexOf(' ') walks back to the start of the word you would have split. Searching within slice(0, room) instead throws away a word that fitted perfectly.

Two things this does not do. It counts UTF-16 code units, so a description containing an emoji can be cut between the halves of a surrogate pair — exercise 100 is that problem in full, and the fix is to work over [...text]. And it says nothing about pixels: the honest way to clamp visible text in a browser is text-overflow: ellipsis in CSS, which knows the font. Truncating in JavaScript is for the places CSS cannot reach, like a <title>, a meta description, an SMS body or a plain-text receipt.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.