给定一个这样的字符串:

"The dog      has a long   tail, and it     is RED!"

什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?

目标:

"The dog has a long tail, and it is RED!"

当前回答

一种更健壮的方法:如果存在初始空格和尾随空格,则该方法也会删除它们。例如:

// NOTE the possible initial and trailing spaces
var str = "  The dog      has a long   tail, and it     is RED!  "

str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// str -> "The dog has a long tail, and it is RED !"

你的例子没有这些空格,但它们也是一个非常常见的场景,而公认的答案只是把它们精简成单个空格,比如:“the…红色!,这不是您通常需要的。

其他回答

还有一种可能:

str.replace( /\s+/g, ' ' )

这是一种解决方案,尽管它将针对所有空格字符:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

编辑:这可能更好,因为它的目标是一个空格后面跟着一个或多个空格:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

替代方法:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

我没有单独使用/\s+/,因为它可以多次替换跨越1个字符的空格,而且可能效率较低,因为它的目标超过了必要的范围。

我没有深入测试任何这些,所以如果有bug,我就不知道了。

另外,如果你要做字符串替换,记得重新分配变量/属性到它自己的替换,例如:

var string = 'foo'
string = string.replace('foo', '')

使用jQuery.prototype.text:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )

这个脚本删除了单词和修饰之间的任何空白(多个空格,制表符,返回值等):

// Trims & replaces any wihtespacing to single space between words
String.prototype.clearExtraSpace = function(){
  var _trimLeft  = /^\s+/,
      _trimRight = /\s+$/,
      _multiple  = /\s+/g;

  return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
};

使用nodepad++函数,下面的regex对我来说很好,

发现:{1}\ \ s + K 替换:留空

鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!