给定一个这样的字符串:

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

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

目标:

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

当前回答

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

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

其他回答

更健壮的:

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 string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

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

var replaced = string.replace(/\s+/g, " ");
var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

编辑: 如果你想替换所有类型的空白字符,最有效的方法是这样的:

str = str.replace(/\s{2,}/g,' ');
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');

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

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