Javascript Regular Expression Remove Spaces
Solution 1:
I would recommend you use the literal notation, and the \s
character class:
//..
return str.replace(/\s/g, '');
//..
There's a difference between using the character class \s
and just ' '
, this will match a lot more white-space characters, for example '\t\r\n'
etc.., looking for ' '
will replace only the ASCII 32 blank space.
The RegExp
constructor is useful when you want to build a dynamic pattern, in this case you don't need it.
Moreover, as you said, "[\s]+"
didn't work with the RegExp
constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s"
(unknown escape)).
Solution 2:
"foo is bar".replace(/ /g, '')
Solution 3:
In production and works across line breaks
This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.
text.replace(/[\n\r\s\t]+/g, ' ')