Javascript正则表达式删除空格 [英] Javascript Regular Expression Remove Spaces
问题描述
所以我正在为JQuery编写一个小插件来删除字符串中的空格。 查看此处
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);
我的正则表达式目前是 [] +
收集所有空间。
这个有效..但是它不会让我的口味很好..
我也试过 [\ s] +
和 [\ W] +
但都没有工作..
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.
推荐答案
我建议您使用文字符号,并使用 \s
字符类:
I would recommend you to use the literal notation, and using the \s
character class:
//..
return str.replace(/\s/g, '');
//..
使用字符类 \s
只需''
,这将匹配更多的空白字符,例如' \\\\ n
等..,寻找''
将只替换ASCII 32空格。
There's a difference between using the character class \s
and just ' '
, this will match a lot of more white-space characters, for example '\t\r\n'
etc.., looking for ' '
will replace only the ASCII 32 blank space.
当你想构建动态模式时, RegExp
构造函数很有用,在这种情况下你不需要它。
The RegExp
constructor is useful when you want to build a dynamic pattern, in this case you don't need it.
此外,如你所说,[\ s] +
didn'使用 RegExp
构造函数,这是因为你传递一个字符串,你应该双重转义反斜杠,否则它们将被解释为内部的字符转义string(例如:\ s===s
(未知逃脱))。
Moreover, as you said, "[\s]+"
didn't worked 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)).
这篇关于Javascript正则表达式删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!