← coderrocketfuel.com

Truncate a String At a Given Length Using JavaScript

How do you truncate or cut off a text string after a certain number of characters and add an ellipsis (...) at the end

To do this, you can create a function that takes two parameters:

  1. string: the original string you wish to truncate.
  2. limit: the number of characters that determines the point where the string will be cut off.

So, when you call the function it should look like this:

truncateString("Sweet potato!", 6)
// returns "Sweet p..."

Notice that the function transforms the "Sweet potato!" string into the "Sweet p.." version which is now 6 characters in length.

Here's what the code for the truncateString() function looks like:

function truncateString(string, limit) {
  if (string.length > limit) {
    return string.substring(0, limit) + "..."
  } else {
    return string
  }
}

If the given string value has a length greater than the limit number given to the function, the function uses the substring() method to return only the part of the string between the start and end indexes (i.e. 0 for the start index and the limit for the end index).

If the given string value's character length is less than or equal to the limit value given to the function, we return the original string without making any modifications.

Here are some test cases for the function:

truncateString("Sweet potato! They taste so good!", 10)
// returns "Sweet pota..."

truncateString("Sweet-potato!", 6)
// returns "Sweet-..."

truncateString("Mashed potatoes are better!", 50)
// returns "Mashed potatoes are better!"

Notice that the first two strings are truncated normally with the ellipsis (...) added to the end. And that the last string has a length of less than 50 characters, so it isn't modified.

For your reference, here's the entire code we've covered in this article:

function truncateString(string, limit) {
  if (string.length > limit) {
    return string.substring(0, limit) + "..."
  } else {
    return string
  }
}

truncateString("Sweet potato! They taste so good!", 10)
// returns "Sweet pota..."

truncateString("Sweet-potato!", 6)
// returns "Sweet-..."

truncateString("Mashed potatoes are better!", 50)
// returns "Mashed potatoes are better!"

Thanks for reading and happy coding!