How to trim whitespace from a string
Short answer
The trim() method strips spaces, tabs and line breaks from both ends:
console.log('[' + ' text '.trim() + ']');Output:
[text]One side only
trimStart() strips the start of the string, trimEnd() the end:
console.log('[' + ' text '.trimStart() + ']');
console.log('[' + ' text '.trimEnd() + ']');Output:
[text ]
[ text]Extra spaces inside the string
trim() leaves the middle of the string alone. A regular expression collapses repeated spaces into one:
console.log('one two three'.replace(/\s+/g, ' '));Output:
one two threeCommon mistake
trim() returns a new string, it does not change the variable. Save the result:
let name = ' Anna ';
name.trim();
console.log('[' + name + ']');
name = name.trim();
console.log('[' + name + ']');Output:
[ Anna ]
[Anna]Functions used in this recipe
- String.prototype.trim — Removes whitespace from both ends of a string.
- String.prototype.trimStart — Removes whitespace and line breaks from the start of a string.
- String.prototype.trimEnd — Removes whitespace and line breaks from the end of a string.