给定一个这样的字符串:

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

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

目标:

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

当前回答

我建议

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

对于空格或

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

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

其他回答

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

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

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

还有一种可能:

str.replace( /\s+/g, ' ' )
let nameCorrection = function (str) {
  let strPerfect = str.replace(/\s+/g, " ").trim();
  let strSmall = strPerfect.toLowerCase();
  let arrSmall = strSmall.split(" ");
  let arrCapital = [];
  for (let x of arrSmall.values()) {
    arrCapital.push(x[0].toUpperCase() + x.slice(1));
  }

  let result = arrCapital.join(" ");
  console.log(result);
};
nameCorrection("Pradeep kumar dHital");

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

// 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, ' ');
};
var myregexp = new RegExp(/ {2,}/g);

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