给定一个这样的字符串:
"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!"
当前回答
我有一个方法,我叫它Derp方法因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了
其他回答
更健壮的:
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 }
我建议
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,' ');
我有一个方法,我叫它Derp方法因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了
尝试用一个空格替换多个空格。
<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>
阅读更多@用单个空格替换多个空格