Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

1234567

Only spaces

If only ordinary spaces should go, replaceAll() is enough:

console.log('+1 555 123 4567'.replaceAll(' ', ''));

Output:

+15551234567

Collapse 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 spaces

Common 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

Thanks for reading!

Donate to the site — we work hard for you.