The String trimStart() method
By Flavio Copes
Learn how the JavaScript trimStart() method returns a new string with the white space removed only from the start, leaving any trailing white space in place.
trimStart() returns a new string with the white space removed from the start of the original string. White space at the end is left in place:
'Testing'.trimStart() //'Testing'
' Testing'.trimStart() //'Testing'
' Testing '.trimStart() //'Testing '
'Testing '.trimStart() //'Testing'
It removes spaces, tabs, newlines and any other Unicode whitespace character.
A string made entirely of white space becomes an empty string. A string with no leading white space comes back unchanged.
The original string is untouched
Strings are immutable in JavaScript, so trimStart() returns a new string:
const city = ' Milan'
const trimmed = city.trimStart()
city //' Milan'
trimmed //'Milan'
If you call the method without using its return value, nothing visible happens. That’s the mistake I see most often. Remember to assign the result.
trimStart() vs trim() vs trimEnd()
The three trimming methods differ in which end they clean:
trim()cleans both endstrimStart()cleans only the beginningtrimEnd()cleans only the end
Most of the time trim() is what you want, for example when cleaning up values typed into a form. Reach for trimStart() when white space at the end matters and you only want to fix the beginning.
A real-world case
Say you’re parsing indented lines from a config file, and you want the content without the indentation:
const line = ' port: 3000'
line.trimStart() //'port: 3000'
The leading spaces are gone, and anything at the end of the line survives.
What about other characters?
Here’s a pitfall: trimStart() only handles white space. It won’t remove other leading characters, like the zeros in '00042'. For those, use a regular expression:
'00042'.replace(/^0+/, '') //'42'
You might also bump into trimLeft() in older codebases. It’s a legacy alias of trimStart(), kept for compatibility. Write trimStart() in new code, it’s the standard name.
Related posts about js: