How to remove all spaces from a string
Short answer
\s in a regular expression means any whitespace character: a space, a tab, a line break:
console.log(' 1 234\t567\n'.replace(/\s/g, ''));Output:
1234567Only spaces
If only ordinary spaces should go, replaceAll() is enough:
console.log('+1 555 123 4567'.replaceAll(' ', ''));Output:
+15551234567Collapse repeated spaces
To keep single spaces between words, replace a group of spaces with one:
console.log('too many spaces'.replace(/\s+/g, ' '));Output:
too many spacesCommon mistake
trim() removes spaces only at the edges, not inside the string:
console.log('[' + ' a b '.trim() + ']');Output:
[a b]Functions used in this recipe
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- String.prototype.trim — Removes whitespace from both ends of a string.