How to trim a String to N characters in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

Trim a String to N characters in JavaScript #

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.

index.js
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:

  1. the start index - the index of the first character to be included in the returned string
  2. the end index - go up to, but not including this index
Indexes are zero-based in JavaScript, which means that the index of the first character in a string is 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.

index.js
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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee