如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
当前回答
以下@rsplak的回答:实际上,使用分割/连接的方式比使用regexp更快。请参见性能测试用例
So
Var result = text。(' ') . join ()
运行速度比
var result = text.replace(/\s+/g, '')
对于小文本,这是不相关的,但对于时间很重要的情况,例如在文本分析器中,特别是在与用户交互时,这是重要的。
另一方面,\s+可以处理更广泛的空格字符。在\n和\t中,它也匹配\u00a0字符,这就是 当使用textDomNode.nodeValue获取文本时,会被返回。
所以我认为这里的结论可以如下:如果你只需要替换空格' ',使用split/join。如果可以有不同符号的符号类-使用replace(/\s+/g, ")
其他回答
如果没有regexp,它只适用于一种情况。
input = input.replace(' ', '');
这是更快的简单! 在某些情况下能帮到你们中的一些人。
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);
点击这里查看工作示例
你还可以使用JS中最新的字符串方法之一:replaceAll
'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
使用replaceAll似乎是最简单、最干净的方法。(我不能保证最快)
“/var/www/site/Brand new document.docx”。替代品(',')
见文档。
replaceAll()方法返回一个新字符串,其中模式的所有匹配项都被替换。模式可以是字符串或RegExp,替换可以是为每个匹配调用的字符串或函数。