Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
599 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...