Emmanuel Akinfulubi

JavaScriptBasic

Truncate a string with an ellipsis in JavaScript

Beginner · 4 min read

Long text often has to fit into a small space: a product name on a card, a message preview in an inbox, a title in a search result. The usual fix is to cut the text and add an ellipsis, the three-dot character …, to show that something was left out. "The quick brown fox jumps over the lazy dog" becomes "The quick brown fox…".

In this tutorial you will write truncate(text, max), which never returns more than max characters, and truncateWords(text, max), which also avoids cutting a word in half. You need to know what a string and a function are.

Two string tools

length tells you how many characters a string has, and slice(start, end) copies the characters from start up to, but not including, end:

JavaScript

const text = 'Hello world';
console.log(text.length);      // 11
console.log(text.slice(0, 5)); // Hello

slice never changes the original string. It gives you a new one.

The ellipsis is one character

The answer uses '\u2026'. That is the escape code for …, a single character that looks like three dots. Writing it as a code keeps the source file plain and makes the character easy to spot.

JavaScript

console.log('\u2026');        // …
console.log('\u2026'.length); // 1
console.log('...'.length);    // 3

Because it is one character, it takes up less of your limit than three full stops would.

Here is the exercise. Try it yourself first if you like, or follow the steps.

37 Truncate text to a length

easy

Shorten text to a maximum length, adding an ellipsis when you cut it. Do not produce something longer than the limit.

Stuck? Three hints, smallest first
  1. 1. The ellipsis counts towards the limit, or your "20 characters" comes out as 23.
  2. 2. Return the text unchanged when it already fits.
  3. 3. Cutting mid-word is ugly; cutting at the last space is nicer. Offer both.

Step 1: leave short text alone

If the text already fits, there is nothing to do:

JavaScript

function truncate(text, max) {
  if (text.length <= max) return text;
  return text.slice(0, max) + '\u2026';
}
console.log(truncate('hi', 20)); // hi

Note the <=. Text that is exactly the limit also fits, and should come back unchanged.

Step 2: spot the overflow

Now try long text with that same function:

JavaScript

function truncate(text, max) {
  if (text.length <= max) return text;
  return text.slice(0, max) + '\u2026';
}
const result = truncate('The quick brown fox jumps over the lazy dog', 20);
console.log(result);        // The quick brown fox …
console.log(result.length); // 21

The caller asked for at most 20 characters and got 21. The ellipsis was added on top of the limit. If that limit exists because a database column or a layout only has room for 20, one character over is enough to break it.

Step 3: make room for the suffix

Cut the text shorter by the suffix's length, so the suffix fits inside the limit. Making the suffix a parameter with a default value lets callers choose '...' or ' (more)' instead:

Step 3

function truncate(text, max, suffix = '\u2026') {
  if (text.length <= max) return text;
  if (max <= suffix.length) return suffix.slice(0, max);
  return text.slice(0, max - suffix.length) + suffix;
}
const long = 'The quick brown fox jumps over the lazy dog';
console.log(truncate(long, 20));        // The quick brown fox…
console.log(truncate(long, 20).length); // 20
console.log(truncate('12345', 5));      // 12345
console.log(truncate('123456', 5));     // 1234…

The middle line handles a tiny limit. If max is 1 and the suffix is …, there is only room for the suffix. If someone passed the three-character '...' with a limit of 2, suffix.slice(0, max) gives '..', so even then the result never goes over.

JavaScript

console.log(truncate('hello', 1));        // …
console.log(truncate('hello', 2, '...')); // ..

Step 4: don't cut words in half

'The quick brown fox jumps' cut at 12 characters gives 'The quick b…', which looks careless. A tidier cut backs up to the last space, so only whole words remain. lastIndexOf(' ') finds the position of the last space in a string, or -1 if there isn't one:

Step 4

function truncateWords(text, max, suffix = '\u2026') {
  if (text.length <= max) return text;
  const cut = text.slice(0, max - suffix.length);
  const lastSpace = cut.lastIndexOf(' ');
  const base = lastSpace > 0 ? cut.slice(0, lastSpace) : cut;
  return base + suffix;
}
const long = 'The quick brown fox jumps over the lazy dog';
console.log(truncateWords(long, 12)); // The quick…
console.log(truncateWords(long, 20)); // The quick brown…
console.log(truncateWords('Supercalifragilistic', 10)); // Supercali…

First cut to the usual length, then back up to the last space. If there is no space at all (one very long word), lastSpace is -1, so we keep the hard cut instead of returning nothing. The result is never longer than truncate's, so it also respects the limit.

Look at the second line. With a limit of 20, the cut is 'The quick brown fox', which happens to end exactly at the end of a word. The function can't see that, so it backs up anyway and drops fox. The result is still correct and within the limit, just shorter than it needed to be. One of the challenges below fixes it.

The full solution

The complete answer has both functions and tries them on a long sentence, a short word, text exactly at the limit and a limit of 1. The checks prove the result never goes over the limit. Press Run to see the output.

The answer

function truncate(text, max, suffix = '\u2026') {
  if (text.length <= max) return text;
  if (max <= suffix.length) return suffix.slice(0, max);
  // The suffix has to fit inside the limit, not be added on top of it.
  return text.slice(0, max - suffix.length) + suffix;
}

// A tidier cut: back up to the last space so words stay whole.
function truncateWords(text, max, suffix = '\u2026') {
  if (text.length <= max) return text;
  const cut = text.slice(0, max - suffix.length);
  const lastSpace = cut.lastIndexOf(' ');
  const base = lastSpace > 0 ? cut.slice(0, lastSpace) : cut;
  return base + suffix;
}

const long = 'The quick brown fox jumps over the lazy dog';

console.log(truncate(long, 20));
console.log(truncateWords(long, 20));
console.log('short text:', truncate('hi', 20));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('never exceeds the limit', truncate(long, 20).length <= 20, true);
test('the cut version', truncate(long, 20), 'The quick brown fox\u2026');
test('short text is unchanged', truncate('hi', 20), 'hi');
test('exactly at the limit is unchanged', truncate('12345', 5), '12345');
test('one over the limit is cut', truncate('123456', 5).length, 5);
test('word-safe version does not split a word', truncateWords(long, 20), 'The quick brown\u2026');
test('and it also respects the limit', truncateWords(long, 20).length <= 20, true);
test('a tiny limit still works', truncate('hello', 1), '\u2026');

The first assertion is the one that matters, and the one most implementations get wrong: if the caller says 20 characters, the result must be at most 20 including the ellipsis. Appending it afterwards gives 21 and breaks whatever layout the limit existed for.

Common mistakes

  • Adding the ellipsis after cutting to the full limit. The result is one character too long. Cut to max - suffix.length.
  • Using < instead of <= for the "fits" check. Text exactly at the limit gets cut for no reason.
  • Returning an empty string when there is no space. One long word would vanish. Fall back to the hard cut.

Try it yourself

  1. Fix the fox case: before backing up, check whether the character right after the cut, text[max - suffix.length], is a space. If it is, the cut already ends on a whole word.
  2. Remove a trailing comma or full stop before the ellipsis, so you never get 'brown,…'.
  3. Write truncateMiddle(text, max) that keeps the start and end and puts the ellipsis in the middle, like 'my-long…name.pdf'.

Keep practising

Newsletter

New writing, when it lands.

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