Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to truncate a string to a given length

Short answer

Take the required number of characters with slice() and add an ellipsis if the string was longer:

const text = 'A very long article title';
const limit = 13;
 
console.log(text.length > limit ? text.slice(0, limit) + '…' : text);

Output:

A very long a…

A helper function

A short string is returned unchanged:

function truncate(text, limit) {
  return text.length > limit ? text.slice(0, limit) + '…' : text;
}
 
console.log(truncate('A very long article title', 13));
console.log(truncate('Short', 13));

Output:

A very long a…
Short

Without cutting a word

Cut to the last space before the limit so that the word stays whole:

const truncateWords = (text, limit) => {
  if (text.length <= limit) return text;
  const cut = text.slice(0, limit);
  const space = cut.lastIndexOf(' ');
  return (space > 0 ? cut.slice(0, space) : cut) + '…';
};
 
console.log(truncateWords('A very long article title', 13));

Output:

A very long…

Common mistake

slice() counts code units, so it can cut an emoji in half. Split the string into characters with ... first:

const text = 'Hi 👋 there';
 
console.log(text.slice(0, 4));
console.log([...text].slice(0, 4).join(''));

Output:

Hi �
Hi 👋

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.