Sometimes, we want to truncate a string in JavaScript.
In this article, we’ll look at how to truncate a string in JavaScript.
How to truncate a string in JavaScript?
To truncate a string in JavaScript, we use the string substring method.
For instance, we write
const truncateString = (str, length) => {
return str.length > length ? str.substring(0, length - 3) + "..." : str;
};
to define the truncateString function.
In it, we str.substring if str.length is bigger than length to return a truncated substring.
Otherwise, we return str.
Conclusion
To truncate a string in JavaScript, we use the string substring method.