给定一个这样的字符串:

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

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

目标:

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

当前回答

鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ 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>

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

鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!

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

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

还有一种可能:

str.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, " ");