Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression Remove Spaces

So i'm writing a tiny little plugin for JQuery to remove spaces from a string. see here

(function($) {     $.stripSpaces = function(str) {         var reg = new RegExp("[ ]+","g");         return str.replace(reg,"");     } })(jQuery); 

my regular expression is currently [ ]+ to collect all spaces. This works.. however It doesn't leave a good taste in my mouth.. I also tried [\s]+ and [\W]+ but neither worked..

There has to be a better (more concise) way of searching for only spaces.

like image 504
rlemon Avatar asked Aug 22 '11 17:08

rlemon


People also ask

How do you remove all the spaces from a string in JS?

Using Split() with Join() method To remove all whitespace characters from the string, use \s instead. That's all about removing all whitespace from a string in JavaScript.

How do I remove blank spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

Can regular expressions have spaces?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.


1 Answers

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)).

like image 179
Christian C. Salvadó Avatar answered Sep 24 '22 07:09

Christian C. Salvadó