How to Truncate a String in JavaScript
Truncating a string sets a limit on the number of characters to display, usually to save space. We can truncate a string in JavaScript by writing a truncate
function that takes the string as the first argument and the maximum number of characters as the second argument.
function truncate(str, length) {
if (str.length > length) {
return str.slice(0, length) + '...';
} else return str;
}
The function truncates the string with the slice
method if it has a character count greater than the specified length. Otherwise, it just returns the same string.
truncate('aaaaaa', 3) // aaa...
truncate('abcde', 4) // abcd...
truncate('aaaaaa', 8) // aaaaaa
We can also write this function in one statement with the JavaScript ternary operator:
function truncate(str, length) {
return str.length > length
? str.slice(0, length) + '...'
: str;
}
This is a String
object, so we can the substr
method in place of slice
to truncate the string:
function truncate(str, length) {
return str.length > length
? str.substr(0, length) + '...'
: str;
}
And we can use ES6 template strings instead of concatenation:
function truncate(str, length) {
return str.length > length
? `${str.substr(0, length)}...`
: str;
}
See also
- How to Extract a Number from a String in JavaScript
- How to Convert a Set to a String in JavaScript
- How to Remove Special Characters From a String in JavaScript
- How to Convert a String to a Boolean in JavaScript
- How to Remove All Vowels From a String in JavaScript
- How to Convert a String to CamelCase in JavaScript