给定一个这样的字符串:
"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!"
当前回答
既然你似乎对性能很感兴趣,我用firebug分析了一下。以下是我得到的结果:
str.replace( / +/g, ' ' ) -> 380ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +(?= )/g, ' ') -> 3250ms
这是在Firefox上,运行100k字符串替换。
如果您认为性能是个问题,我鼓励您使用firebug进行自己的分析测试。众所周知,人类不善于预测程序的瓶颈所在。
(另外,请注意,IE 8的开发者工具栏也有内置的分析器——它可能值得检查在IE中的性能是什么样的。)
其他回答
还有一种可能:
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, " ");
var text = `xxx df dfvdfv df
dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');
结果:
"xxx df dfvdfv df dfv"
//将多个空格替换为一个空格
String replacedDisplayName = displayName.replaceAll("\\s{2,}", " ");
既然你似乎对性能很感兴趣,我用firebug分析了一下。以下是我得到的结果:
str.replace( / +/g, ' ' ) -> 380ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +(?= )/g, ' ') -> 3250ms
这是在Firefox上,运行100k字符串替换。
如果您认为性能是个问题,我鼓励您使用firebug进行自己的分析测试。众所周知,人类不善于预测程序的瓶颈所在。
(另外,请注意,IE 8的开发者工具栏也有内置的分析器——它可能值得检查在IE中的性能是什么样的。)