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

输入:

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

输出:

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

当前回答

使用replaceAll似乎是最简单、最干净的方法。(我不能保证最快)

“/var/www/site/Brand new document.docx”。替代品(',')

见文档。

replaceAll()方法返回一个新字符串,其中模式的所有匹配项都被替换。模式可以是字符串或RegExp,替换可以是为每个匹配调用的字符串或函数。

其他回答

使用replaceAll似乎是最简单、最干净的方法。(我不能保证最快)

“/var/www/site/Brand new document.docx”。替代品(',')

见文档。

replaceAll()方法返回一个新字符串,其中模式的所有匹配项都被替换。模式可以是字符串或RegExp,替换可以是为每个匹配调用的字符串或函数。

你可以使用regex从字符串中移除空格

let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');

你还可以使用JS中最新的字符串方法之一:replaceAll

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
  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',它就忽略了大小写敏感性。

参考请点击这里。

正则表达式+ Replace()

虽然regex可能更慢,但在很多情况下,开发人员一次只操作几个字符串,所以考虑速度是无关紧要的。尽管/ /比/\s/快,但是使用'\s'可能更清楚地向其他开发人员解释了正在发生的事情。

let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'

Split() + Join()

使用Split + Join可以对字符串进行进一步的链式操作。

let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";