如何从 JavaScript 中的文本中删除多余的空格(即一行中的多个空格字符)?
例如
match the start using.
如何删除“match”和“the”之间除一个空格以外的所有空格?
最佳答案
使用正则表达式。示例代码如下:
var string = 'match the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');
为了获得更好的性能,请使用以下正则表达式:
string = string.replace(/ +/g, ' ');
使用 firebug 分析结果如下:
str.replace(/ +/g, ' ') -> 790ms
str.replace(/ +/g, ' ') -> 380ms
str.replace(/ {2,}/g, ' ') -> 470ms
str.replace(/\s\s+/g, ' ') -> 390ms
str.replace(/ +(?= )/g, ' ') -> 3250ms
关于javascript - 如何在 JavaScript 中删除字符串中多余的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155566/