Truncate string and add ellipsis in JavaScript
Today we’ll show you how to truncate string and add ellipsis in JavaScript. In this short article, we will show you how to cut off a text 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 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"
That’s it for today.
Thank you for reading. Happy Coding..!!