Borislav Hadzhiev
Sat Oct 09 2021·2 min read
Photo by Johannes Plenio
To trim a string to N characters, use the substring()
method, passing it a
starting index of 0
and an end index of the desired string length. The
substring
method returns the part of the string between the start and end
indexes.
const str = 'Hello World Goodbye World'; const length = 11; const trimmed = str.substring(0, length); console.log(trimmed); // 👉️ Hello World
We used the String.substring method to trim a string to 11 characters.
The parameters we passed to the method are:
0
and the index of the last character is str.length - 1
.If you need to add ellipsis to the truncated string in case there are remaining characters, you can use a ternary operator.
const str = 'Hello World Goodbye World'; const length = 11; const trimmed = str.length > length ? str.substring(0, length) + '...' : str.substring(0, length); console.log(trimmed); // 👉️ Hello World...
The ternary operator is very similar to an if / else statement.
We first check if the string's length is greater than how many characters we want to trim off the string. If it is, we have to add ellipsis.
The code snippet above is equivalent to the following if/else statement.
const str = 'Hello World Goodbye World'; const length = 11; let trimmed; if (str.length > length) { trimmed = str.substring(0, length) + '...'; } else { trimmed = str.substring(0, length); } console.log(trimmed) // 👉️ Hello World...
Definitely not elegant as the ternary operator, however it's easier to read if you're not used to the syntax.