给定一个这样的字符串:

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

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

目标:

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

当前回答

var text = `xxx  df dfvdfv  df    
                     dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');

结果:

"xxx df dfvdfv df dfv"

其他回答

更健壮的:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}

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

下面就是:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

或者如果你也想替换制表符:

var replaced = string.replace(/\s+/g, " ");

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

// 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…红色!,这不是您通常需要的。

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

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