正则表达式删除空格

因此,我正在为 JQuery 编写一个小小的插件来从字符串中删除空格

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

我的正则表达式目前是 [ ]+来收集所有空格。 这个管用. . 但是它不会在我嘴里留下好的味道. 。 我也试过 [\s]+[\W]+,但都没用。

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

273651 次浏览

这个也可以: http://jsfiddle.net/maniator/ge59E/3/

var reg = new RegExp(" ","g"); //<< just look for a space.
str.replace(/\s/g,'')

我没问题。

jQuery.trim对 IE 有以下的改进,尽管我不确定它会影响到什么版本:

// 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]+$/;
}
"foo is bar".replace(/ /g, '')

我建议您使用文字表示法和 \s字符类:

//..
return str.replace(/\s/g, '');
//..

使用字符类 \s和仅使用 ' '是有区别的,这将匹配更多的空白字符,例如 '\t\r\n'等。,寻找 ' '将只替换 ASCII 32空格。

当您希望 build是一个动态模式时,RegExp构造函数非常有用,在这种情况下您不需要它。

此外,正如您所说,"[\s]+"不能与 RegExp构造函数一起工作,这是因为您正在传递一个字符串,并且您应该“双转义”反斜杠,否则它们将被解释为字符在字符串内转义(例如: "\s" === "s"(未知转义))。

删除字符串中的所有空格

// 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"

在生产和跨行工作中

这在一些应用程序中被用来清理用户生成内容,去除额外的空格/返回值等,但保留了空格的含义。

text.replace(/[\n\r\s\t]+/g, ' ')

两者都应该有效:

    text.replace(/ +/g,' ')

或者:

    text.replace(/ {2,}/g, ' ')

const text = "eat healthy     and  drink  gallon of  water."




text.replace(/ +/g,' ')
// eat healthy and drink gallon of water.


text.replace(/ {2,}/g, ' ')
// eat healthy and drink gallon of water.