Sometimes, we may want to truncate long strings in our JavaScript code.
In this article, we’ll look at some good ways to truncate long strings in JavaScript.
Using the String.prototype.substr Method
We can use the string instance’s substr
method to return a substring given the start and end indexes.
For instance, we can write:
const truncate = (str, n) => {
return (str.length > n) ? str.substr(0, n - 1) + '...' : str;
};
console.log(truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 10))
We create the truncate
function with the str
parameter that takes the string.
n
is the number of characters to truncate to.
And we return the substring returned by the substr
method with the start and end indexes if the string’s length is longer than n
.
Otherwise, we return the whole string.
Therefore, the console log should log 'Lorem ips…’
since we truncate the string to 10 characters in length.
String.prototype.replace Method
We can use the string replace
method with a regex to truncate a string.
To use it, we write:
const truncate = (str, n) => {
return str.replace(new RegExp(`(.{${n-1}})..+`), "$1...");
};
console.log(truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 10))
We call replace
with a regex that takes the n
value and matches the first n-1
characters of the string.
Then in the 2nd argument, we use the $1
placeholder to get the matched string and then add ...
after it.
Therefore, in the console log, we get the same result as before.
Lodash truncate Method
Another way to truncate a string easily is to use the Lodash truncate
method.
For instance, we can write:
const truncated = _.truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', {
length: 12
});
console.log(truncated)
to call the truncate
method to truncate the string.
The first argument is the string to truncate.
And the 2nd argument is the options for truncating.
We set length
to 12 to truncate the string to 12 characters long including the ellipsis.
Therefore, truncated
is 'Lorem ips…’
is the value of truncated
.
Conclusion
We can use plain JavaScript string methods or Lodash truncate
method to truncate a string in JavaScript.