Borislav Hadzhiev
Tue Oct 26 2021·1 min read
Photo by Tony Ross
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.
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.
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.
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.
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.