给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
当前回答
假设你还想覆盖制表符、换行符等,只需将\s\s+替换为' ':
string = string.replace(/\s\s+/g, ' ');
如果你真的只想覆盖空格(而不是制表符,换行符等),可以这样做:
string = string.replace(/ +/g, ' ');
其他回答
还有一种可能:
str.replace( /\s+/g, ' ' )
我知道我迟到了,但我发现了一个很好的解决方案。
下面就是:
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, " ");
var myregexp = new RegExp(/ {2,}/g);
str = str.replace(myregexp,' ');
尝试用一个空格替换多个空格。
<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>
阅读更多@用单个空格替换多个空格