如何在JavaScript中删除字符串中的额外空格? [英] How can I remove extra white space in a string in JavaScript?

查看:73
本文介绍了如何在JavaScript中删除字符串中的额外空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从JavaScript中的文本中删除多余的空格(即一行中多个空白字符)?

How can I remove extra white space (i.e. more than one white space character in a row) from text in JavaScript?

例如

match    the start using.

如何删除匹配和该之间的所有空格?

How can I remove all but one of the spaces between "match" and "the"?

推荐答案

使用正则表达式。示例代码如下:

Use regex. Example code below:

var string = 'match    the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');

为了获得更好的性能,请使用以下正则表达式:

For better performance, use below regex:

string = string.replace(/ +/g, ' ');

使用firebug进行分析后得到以下结果:

Profiling with firebug resulted in following:

str.replace(/ +/g, ' ')        ->  790ms
str.replace(/ +/g, ' ')       ->  380ms
str.replace(/ {2,}/g, ' ')     ->  470ms
str.replace(/\s\s+/g, ' ')     ->  390ms
str.replace(/ +(?= )/g, ' ')    -> 3250ms

这篇关于如何在JavaScript中删除字符串中的额外空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆