如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
如何删除字符串中的空格?例如:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
当前回答
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 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',它就忽略了大小写敏感性。
参考请点击这里。
这个吗?
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是“全局”标志,意思是匹配所有(空白)。
关于+的一个很好的解释可以在这里找到。
作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空白替换为任何其他字符串。
你还可以使用JS中最新的字符串方法之一:replaceAll
'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
从字符串中删除空格最简单的方法是使用replace
let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
简单的方法
someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');