Remove leading and trailing Spaces from a String in JS

avatar

Borislav Hadzhiev

Tue Oct 26 20211 min read

Remove leading and trailing Spaces from a String #

Use the trim() method to remove the leading and trailing spaces from a string. The trim method returns a new string representing the original string stripped of any leading and trailing whitespace.

index.js
const str = ' avocado '; // ๐Ÿ‘‡๏ธ remove leading and trailing spaces const withoutTrailingSpaces = str.trim(); console.log(withoutTrailingSpaces); // ๐Ÿ‘‰๏ธ "avocado"
The trim method removes any whitespace characters include spaces, tabs and newlines.

We used the String.trim method to get a copy of the string with the leading and trailing spaces removed.

The trim method does not change the original string, instead it returns a new string stripped of any leading whitespace. Strings are immutable in JavaScript.

If the string contains no leading or trailing spaces, the trim method returns a copy of the original string and does not throw an error.

index.js
const str = 'avocado'.trim(); console.log(str); // ๐Ÿ‘‰๏ธ "avocado"

When the trim method is used on a string that contains leading or trailing spaces, the new string has a new length.

index.js
const str = ' avocado '; console.log(str.length); // ๐Ÿ‘‰๏ธ 11 const trimmed = str.trim(); console.log(trimmed.length); // ๐Ÿ‘‰๏ธ 7

If you only want to trim the leading spaces of a string, use the trimStart() method instead.

And to trim only the trailing spaces of a string, use the trimEnd() method.

Further Reading #

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