How to truncate a string in JavaScript
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.
- 5 Awesome JavaScript String Tips
- Load script dynamically and add the callback in JavaScript
- How to generate a random n digit number using JavaScript
- How to round a number to 2 decimal places in JavaScript
- Sorting an array in JavaScript
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..!!