给定一个这样的字符串:

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

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

目标:

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

当前回答

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

// 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, ' ');
};

其他回答

我建议

string = string.replace(/ +/g," ");

对于空格或

string = string.replace(/(\s)+/g,"$1");

还可以将多个退货转换为单个退货。

我知道我迟到了,但我发现了一个很好的解决方案。

下面就是:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');

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

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

我有一个方法,我叫它Derp方法因为没有更好的名字。

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了

//将多个空格替换为一个空格

String replacedDisplayName = displayName.replaceAll("\\s{2,}", " ");