Remove Trailing Spaces from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20211 min read

banner

Photo by Tony Ross

Remove Trailing Spaces from a String #

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

index.js
const str = ' apple '; // ๐Ÿ‘‡๏ธ remove trailing spaces const withoutTrailingSpaces = str.trimEnd(); console.log(withoutTrailingSpaces); // ๐Ÿ‘‰๏ธ " apple" // ๐Ÿ‘‡๏ธ remove both leading and trailing spaces const withoutLeadingAndTrailing = str.trim(); console.log(withoutLeadingAndTrailing); // ๐Ÿ‘‰๏ธ "apple"

We used the String.trimEnd method to remove the trailing spaces from a string.

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

If the string contains no trailing spaces, the trimEnd method returns a copy of the original string, without throwing any errors.

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

When the trimEnd method is used on a string that contains trailing spaces, the new string has an updated length.

index.js
const str = 'test '; console.log(str.length); // ๐Ÿ‘‰๏ธ 8 const trimmed = str.trimEnd(); console.log(trimmed.length); // ๐Ÿ‘‰๏ธ 4

If you want to remove the leading and trailing space from a string, use the trim method instead.

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