给定一个这样的字符串:

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

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

目标:

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

当前回答

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

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

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

其他回答

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

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

var replaced = string.replace(/\s+/g, " ");
var myregexp = new RegExp(/ {2,}/g);

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

以下是对我来说很有效的解决方案:

var text = “ Tes ddas dMd WAlkman 3Dsfd ” .toLowerCase() .replace(/\b\s+/g, “ ”) .replace(/\b\w/g, s => s.toUpperCase()) .trimStart() .trimEnd(); 控制台.log(文本); 结果: Tes Ddas Dmd 随身听 3dsfd

我建议

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

对于空格或

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

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

尝试用一个空格替换多个空格。

<script type="text/javascript">
    var myStr = "The dog      has a long   tail, and it     is RED!";
    alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'

    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
</script>

阅读更多@用单个空格替换多个空格