如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
当前回答
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
输出:
你好世界
其他回答
你可以使用regex从字符串中移除空格
let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
这个吗?
str = str.replace(/\s/g, '');
例子
var str = '/var/www/site/Brand new document.docx'; document.write( str.replace(/\s/g, '') );
更新:基于这个问题,如下:
str = str.replace(/\s+/g, '');
是更好的解决方案。它产生相同的结果,但速度更快。
正则表达式
\s是“空白”的正则表达式,g是“全局”标志,意思是匹配所有(空白)。
关于+的一个很好的解释可以在这里找到。
作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空白替换为任何其他字符串。
var input = '/var/www/site/Brand new document.docx';
//remove space
input = input.replace(/\s/g, '');
//make string lower
input = input.toLowerCase();
alert(input);
点击这里查看工作示例
var a = b = " /var/www/site/Brand new document.docx "; Console.log (a.split(' ').join(")); Console.log (b.replace(/\s/g, "));
有两种方法!
以下@rsplak的回答:实际上,使用分割/连接的方式比使用regexp更快。请参见性能测试用例
So
Var result = text。(' ') . join ()
运行速度比
var result = text.replace(/\s+/g, '')
对于小文本,这是不相关的,但对于时间很重要的情况,例如在文本分析器中,特别是在与用户交互时,这是重要的。
另一方面,\s+可以处理更广泛的空格字符。在\n和\t中,它也匹配\u00a0字符,这就是 当使用textDomNode.nodeValue获取文本时,会被返回。
所以我认为这里的结论可以如下:如果你只需要替换空格' ',使用split/join。如果可以有不同符号的符号类-使用replace(/\s+/g, ")