The String trim() method
By Flavio Copes
Learn how the JavaScript trim() method returns a new string with the white space removed from the beginning and the end, leaving the original string untouched.
trim() returns a new string with the white space removed from the beginning and the end of the original string:
'Testing'.trim() //'Testing'
' Testing'.trim() //'Testing'
' Testing '.trim() //'Testing'
'Testing '.trim() //'Testing'
Strings in JavaScript are immutable, so trim() never changes the string you call it on. It always gives you a new one back:
const name = ' Flavio '
const clean = name.trim()
name //' Flavio '
clean //'Flavio'
When do you need it?
The classic case is user input. People copy and paste values into forms, and stray spaces come along for the ride. An email address like ' flavio@test.com ' will fail validation or create a duplicate account, so you trim it before doing anything else:
const email = document.querySelector('#email').value.trim()
Another common one is data from files or APIs, where lines often end with an invisible newline character.
What counts as white space?
More than the space character. trim() also removes tabs, newlines, carriage returns and other Unicode white space:
'\t Testing \n'.trim() //'Testing'
That’s why it works well on lines read from a text file: the trailing \n disappears too.
Trimming only one side
If you only want to clean one end, use trimStart() and trimEnd():
' Testing '.trimStart() //'Testing '
' Testing '.trimEnd() //' Testing'
They follow the same rules as trim(), just limited to one side of the string.
The pitfall: spaces in the middle
trim() only touches the edges. It does not remove or collapse white space inside the string:
' hello world '.trim() //'hello world'
If you expected 'hello world', that’s not what you get. To collapse the inner spaces too, combine trim() with replace() and a regular expression:
' hello world '.trim().replace(/\s+/g, ' ') //'hello world'
The regex matches every run of white space and replaces it with a single space.
One last thing: calling trim() on something that’s not a string throws an error. If a form value might be null or undefined, guard it first, for example with (value ?? '').trim().
Related posts about js: