简体   繁体   English

Javascript正则表达式删除空格

[英]Javascript Regular Expression Remove Spaces

So i'm writing a tiny little plugin for JQuery to remove spaces from a string.所以我正在为 JQuery 编写一个小插件来从字符串中删除空格。 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..这有效..但是它不会在我嘴里留下好味道..我也尝试过[\\s]+[\\W]+但都没有奏效..

There has to be a better (more concise) way of searching for only spaces.必须有一种更好(更简洁)的方法来仅搜索空格。

I would recommend you use the literal notation, and the \\s character class:我建议您使用文字符号和\\s字符类:

//..
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.使用字符类\\s和仅使用' '之间存在差异,这将匹配更多的空白字符,例如'\\t\\r\\n'等,查找' '将仅替换 ASCII 32空格处。

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it. RegExp构造函数在您想要构建动态模式时很有用,在这种情况下您不需要它。

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 (eg: "\\s" === "s" (unknown escape)).此外,正如您所说, "[\\s]+"不适用于RegExp构造函数,那是因为您正在传递一个字符串,您应该“双重转义”反斜杠,否则它们将被解释为字符转义字符串内部(例如: "\\s" === "s" (未知转义))。

"foo is bar".replace(/ /g, '')

Remove all spaces in string删除字符串中的所有空格

// Remove only spaces
`
Text with spaces 1 1     1     1 
and some
breaklines

`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines

"

// Remove spaces and breaklines
`
Text with spaces 1 1     1     1
and some
breaklines

`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"

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, ' ')
str.replace(/\s/g,'')

Works for me.为我工作。

jQuery.trim has the following hack for IE, although I'm not sure what versions it affects: jQuery.trim对 IE 有以下 hack,虽然我不确定它会影响哪些版本:

// Check if a string has a non-whitespace character in it
rnotwhite = /\S/

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
    trimLeft = /^[\s\xA0]+/;
    trimRight = /[\s\xA0]+$/;
}

这也适用: http : //jsfiddle.net/maniator/ge59E/3/

var reg = new RegExp(" ","g"); //<< just look for a space.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM