Truncate a string at a word boundary in JavaScript
Intermediate · 4 min read
Blog previews, product cards and notification banners all show a shortened version of longer text, ending in …. Cutting at a fixed number of characters is easy. Doing it well means not chopping a word in half, so you get 'The quick…' and never 'The quick br…'.
In this tutorial you will write truncate(text, max). It keeps the result within max characters, counting the ellipsis, and steps back to the last whole word. You should know slice, lastIndexOf and string length. Everything else is explained as we go.
The rules we are building
- If the text already fits, return it unchanged.
- The ellipsis is part of the limit.
…is one character, so the text itself getsmax - 1characters. We call that the budget. - If the cut lands in the middle of a word, step back to the last space.
- A single word longer than the budget has no space to step back to, so it gets cut anyway.
Why one ellipsis character
… is a single Unicode character, and '…'.length is 1. Three dots, '...', are three characters. If your limit is tight, such as a field that accepts at most 140 characters, the single character saves two.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
47 Truncate with an ellipsis at a word boundary
fairShorten a sentence to at most n characters, ending with an ellipsis, without cutting a word in half. The ellipsis counts towards the limit.
Stuck? Three hints, smallest first
- 1. Budget one character for the ellipsis, so the body gets
max - 1. - 2. Look at the character just past the cut to tell whether you landed mid-word.
- 3. A single word longer than the limit has no space to step back to, so it must be cut.
Step 1: return short text untouched
const line = 'The quick brown fox jumps';
console.log(line.length); // 25
Our sample sentence is 25 characters long. For any max of 25 or more there is nothing to do, so the function starts with if (text.length <= max) return text;.
Step 2: cut to the budget, the natural wrong turn
const line = 'The quick brown fox jumps';
const max = 12;
const cut = line.slice(0, max - 1) + '…';
console.log(cut); // 'The quick b…'
console.log(cut.length); // 12
The length is right, but the word brown has been chopped down to b. We need to notice that and step back.
Step 3: did we land mid-word?
Look at the character just past the cut. If it is a space, the cut fell between two words and the body ends on a whole word. If it is a letter, we are in the middle of one:
const line = 'The quick brown fox jumps';
console.log(JSON.stringify(line[11])); // "r"
console.log(JSON.stringify(line[9])); // " "
With a budget of 11, line[11] is r, inside brown. With a budget of 9, line[9] is the space after quick. JSON.stringify adds quotes so you can see the space.
Step 4: step back to the last space
const line = 'The quick brown fox jumps';
let body = line.slice(0, 11); // 'The quick b'
const at = body.lastIndexOf(' ');
console.log(at); // 9
body = body.slice(0, at);
console.log(body + '…'); // 'The quick…'
lastIndexOf(' ') finds the position of the last space in the body. Slicing up to it drops the half word. The result is shorter than the limit, which is fine: the rule is "at most max".
Step 5: put it in a function
function truncate(text, max) {
if (text.length <= max) return text;
const budget = max - 1;
let body = text.slice(0, budget);
if (text[budget] !== ' ') {
const at = body.lastIndexOf(' ');
if (at !== -1) body = body.slice(0, at);
}
return body.trimEnd() + '…';
}
const line = 'The quick brown fox jumps';
console.log(truncate(line, 30)); // 'The quick brown fox jumps'
console.log(truncate(line, 12)); // 'The quick…'
console.log(truncate(line, 10)); // 'The quick…'
console.log(truncate('Antidisestablishmentarianism', 10)); // 'Antidises…'
lastIndexOf returns -1 when there is no space at all. That is the one-long-word case, so if (at !== -1) leaves the hard cut in place. With a limit of 10, the budget is 9 and text[9] is a space, so the cut is already clean and no stepping back is needed.
Step 6: why trimEnd is there
function truncate(text, max) {
if (text.length <= max) return text;
const budget = max - 1;
let body = text.slice(0, budget);
if (text[budget] !== ' ') {
const at = body.lastIndexOf(' ');
if (at !== -1) body = body.slice(0, at);
}
return body.trimEnd() + '…';
}
console.log(truncate('The quick brown', 8)); // 'The…'
console.log(truncate('The quick brown fox jumps', 3)); // 'Th…'
With a double space, stepping back to the last space can leave the body ending in another space, and 'The …' looks like a mistake. trimEnd() removes trailing whitespace so the ellipsis sits right after the word. The second line shows a tiny limit still fits: two characters plus the ellipsis.
The full solution
The panel has truncate and a loop that prints the sentence at several limits. Press Run and watch how the result changes as the limit shrinks, then read the checks underneath.
function truncate(text, max) {
if (text.length <= max) return text;
const budget = max - 1; // one character goes to the ellipsis
let body = text.slice(0, budget);
if (text[budget] !== ' ') { // the cut landed mid-word, so step back
const at = body.lastIndexOf(' ');
if (at !== -1) body = body.slice(0, at);
}
return body.trimEnd() + '…';
}
const line = 'The quick brown fox jumps';
for (const n of [30, 25, 12, 10, 4, 3]) {
console.log(String(n).padStart(2), JSON.stringify(truncate(line, n)));
}
Output
10 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 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a short string is returned untouched', truncate(line, 30), line);
test('exactly the limit is untouched too', truncate(line, 25), line);
test('a cut that lands on a space keeps the whole word', truncate(line, 10), 'The quick…');
test('a cut mid-word steps back to the space', truncate(line, 12), 'The quick…');
test('so the result can be shorter than the limit', truncate(line, 12).length <= 12, true);
test('the ellipsis is ONE character, not three dots', '…'.length, 1);
test('a single long word is cut hard, having no space to step back to', truncate('Antidisestablishmentarianism', 10), 'Antidises…');
test('a double space leaves no gap before the ellipsis', truncate('The quick brown', 8), 'The…');
test('and the tiniest limit still fits', truncate(line, 3), 'Th…');
test('every result respects the limit', [30, 25, 12, 10, 4, 3].every((n) => truncate(line, n).length <= n), true);
The ellipsis has to come out of the budget, or "truncate to 140" produces 142 characters and the API rejects it. Using '...' instead costs three, which is the main practical reason to prefer the single … character.
trimEnd() at the end is not decoration. Stepping back to the last space can leave the body ending in whitespace when the text had a double space, and 'The …' looks like a mistake.
This measures in code units, so a limit near an emoji can still cut a surrogate pair. Where that matters, walk [...text] or segment it, as in exercise 39.
Common mistakes
- Adding the ellipsis on top of the limit.
text.slice(0, max) + '…'is one character too long. Take it out of the budget. - Using three dots.
'...'costs three characters. Use the single…character. - Forgetting the one-long-word case. Without the
at !== -1check,slice(0, -1)chops one character off the end instead of stepping back.
Try it yourself
- Change
truncateto use'...'as the ending and make sure the result still never goes overmax. - Add a
minimumso a preview never steps back to fewer than half the limit. - Write a version that counts by code point with
[...text], so an emoji is never cut in half.