给定一个这样的字符串:
"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!"
当前回答
var str = "The dog has a long tail, and it is RED!";
str = str.replace(/ {2,}/g,' ');
编辑: 如果你想替换所有类型的空白字符,最有效的方法是这样的:
str = str.replace(/\s{2,}/g,' ');
其他回答
以下是对我来说很有效的解决方案:
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
我知道我们必须使用正则表达式,但在一次采访中,我被要求不要使用正则表达式。
@slightlytyler帮助我提出了下面的方法。
const testStr = "I LOVE STACKOVERFLOW LOL"; const removeSpaces = str => { Const chars = str.split("); const nextChars = char .reduce( (acc, c) => { If (c === ' ') { const lastChar = acc[acc.]长度- 1]; if (lastChar === ' ') { 返回acc; } } 返回[…acc, c]; }, [], ); const nextStr = nextchar .join("); 返回nextStr }; console.log (removeSpaces (testStr));
我知道我迟到了,但我发现了一个很好的解决方案。
下面就是:
var myStr = myStr.replace(/[ ][ ]*/g, ' ');
既然你似乎对性能很感兴趣,我用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中的性能是什么样的。)
我们可以在sed system命令的帮助下使用下面的正则表达式。类似的正则表达式可用于其他语言和平台。
将文本添加到某个文件中,例如test
manjeet-laptop:Desktop manjeet$ cat test
"The dog has a long tail, and it is RED!"
我们可以使用下面的正则表达式将所有空格替换为单个空格
manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"
希望这能起到作用