The String trimEnd() method
By Flavio Copes
Learn how the JavaScript trimEnd() method returns a new string with the white space removed only from the end, leaving any leading white space in place.
trimEnd() returns a new string with the white space removed from the end of the original string. White space at the start stays where it is:
'Testing'.trimEnd() //'Testing'
' Testing'.trimEnd() //' Testing'
' Testing '.trimEnd() //' Testing'
'Testing '.trimEnd() //'Testing'
White space here means spaces, tabs, newlines and any other Unicode whitespace character.
If the string is nothing but white space, you get an empty string back. If there’s nothing to remove, you get an identical string.
It doesn’t change the original string
Strings in JavaScript are immutable. trimEnd() gives you a new string and leaves the original alone:
const name = 'Flavio '
const trimmed = name.trimEnd()
name //'Flavio '
trimmed //'Flavio'
This is a classic pitfall: calling name.trimEnd() and throwing away the result does nothing. Assign the result to a variable.
How is it different from trim() and trimStart()?
The three methods are siblings:
trim()removes white space from both endstrimStart()removes it only from the starttrimEnd()removes it only from the end
Use trimEnd() when the leading white space is meaningful and you want to keep it. Indentation, for example.
A real-world case
Reading lines from a file or from user input often leaves a trailing newline attached:
const line = 'order shipped\n'
line.trimEnd() //'order shipped'
Without trimming, a comparison like line === 'order shipped' fails, and the invisible newline makes it a confusing bug to track down. Trim the end before comparing and the problem goes away.
What it can’t do
trimEnd() only removes white space. You can’t tell it to strip other characters. To remove, say, trailing zeros from a number string, use a regular expression instead:
'12.50000'.replace(/0+$/, '') //'12.5'
One last note: you might see trimRight() in older code. It’s an alias of trimEnd(), kept around for compatibility with code written before the name was standardized. Use trimEnd() in new code.
Related posts about js: