How to Truncate a String in JavaScript

Last updated on May 16, 2022
How to Truncate a String in JavaScript

Truncating a string sets a limit on the number of characters to display, usually to save space. We can truncate a string in JavaScript by writing a truncate function that takes the string as the first argument and the maximum number of characters as the second argument.

function truncate(str, length) {
  if (str.length > length) {
    return str.slice(0, length) + '...';
  } else return str;
}

The function truncates the string with the slice method if it has a character count greater than the specified length. Otherwise, it just returns the same string.

truncate('aaaaaa', 3)    // aaa...
truncate('abcde', 4)    // abcd...
truncate('aaaaaa', 8)    // aaaaaa

We can also write this function in one statement with the JavaScript ternary operator:

function truncate(str, length) {
  return str.length > length
    ? str.slice(0, length) + '...'
    : str;
}

This is a String object, so we can the substr method in place of slice to truncate the string:

function truncate(str, length) {
  return str.length > length
    ? str.substr(0, length) + '...'
    : str;
}

And we can use ES6 template strings instead of concatenation:

function truncate(str, length) {
  return str.length > length
    ? `${str.substr(0, length)}...`
    : str;
}
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also