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;
}


Subscribe to Coding Beauty Newsletter

Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.


Leave a Comment

Your email address will not be published. Required fields are marked *