如何删除字符串中的空格?例如:

输入:

'/var/www/site/Brand new document.docx'

输出:

'/var/www/site/Brandnewdocument.docx'

当前回答

最短和最快:str.replace(/ /g, ");


基准:

以下是我的结果- (2018.07.13)MacOs High Sierra 10.13.3在Chrome 67.0.3396(64位),Safari 11.0.3 (13604.5.6), Firefox 59.0.2(64位)):

短的字符串

短字符串类似于OP问题中的例子

在所有浏览器上最快的解决方案是/ /g (regexp1a) - Chrome 17.7M(操作/秒),Safari 10.1M, Firefox 8.8M。对于所有浏览器来说,最慢的是拆分连接解决方案。更改\s或向regexp添加+或i会降低处理速度。

长字符串

对于大约300万个字符的字符串,结果如下:

regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95 regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26 火狐26.41,Safari 23.10, Chrome 7.98,

您可以在您的机器上运行它:https://jsperf.com/remove-string-spaces/1

其他回答

  var output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); 
    or
  var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");

注意:虽然你使用'g'或'gi'来删除空格,但它们的行为是一样的。

如果我们在replace函数中使用'g',它将检查完全匹配。但如果我们使用'gi',它就忽略了大小写敏感性。

参考请点击这里。

var input = '/var/www/site/Brand new document.docx';

//remove space
input = input.replace(/\s/g, '');

//make string lower
input = input.toLowerCase();

alert(input);

点击这里查看工作示例

简单的方法

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');

var a = b = " /var/www/site/Brand new document.docx "; Console.log (a.split(' ').join(")); Console.log (b.replace(/\s/g, "));

有两种方法!

最短和最快:str.replace(/ /g, ");


基准:

以下是我的结果- (2018.07.13)MacOs High Sierra 10.13.3在Chrome 67.0.3396(64位),Safari 11.0.3 (13604.5.6), Firefox 59.0.2(64位)):

短的字符串

短字符串类似于OP问题中的例子

在所有浏览器上最快的解决方案是/ /g (regexp1a) - Chrome 17.7M(操作/秒),Safari 10.1M, Firefox 8.8M。对于所有浏览器来说,最慢的是拆分连接解决方案。更改\s或向regexp添加+或i会降低处理速度。

长字符串

对于大约300万个字符的字符串,结果如下:

regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95 regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26 火狐26.41,Safari 23.10, Chrome 7.98,

您可以在您的机器上运行它:https://jsperf.com/remove-string-spaces/1