• Post category:JavaScript
  • Reading time:3 mins read

Today we’ll show you how to truncate a string and add ellipsis in JavaScript. In this short article, we will show you how to cut off a text if it is longer than the specified number of characters and add the triple dots or ellipsis (...) using JavaScript function.

There are multiple ways to do this but here, we will discuss the pure JavaScript method. You can also use the third party library for several functions.

Custom function to truncate a string and add ellipsis

Let’s create a custom function where we will pass the two parameters named str that stands for original string and n is the number that used to truncate the original string after a certain number of the character. Use the following custom function to truncate the string.

function truncateString(str, n) {
  if (str.length > n) {
    return str.substring(0, n) + "...";
  } else {
    return str;
  }
}

Here, we have compared the string length with the given number and use the substring() function to cut off a text. Let’s test the above function with some of the examples and see how it works.

truncateString("Lorem Ipsum is simply dummy text", 11);
// Output: "Lorem Ipsum..."

truncateString("Lorem Ipsum is simply dummy text", 5);
// Output: "Lorem..."

truncateString("Lorem Ipsum is simply dummy text", 100);
// Output: "Lorem Ipsum is simply dummy text"

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply