Remove Trailing Spaces from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.