如何使用JavaScript从string中删除空格?

如何删除string中的空格? 例如:

input: '/var/www/site/Brand new document.docx'
输出: '/var/www/site/Brandnewdocument.docx'

谢谢

这个?

 str = str.replace(/\s/g, ''); 

 var str = '/var/www/site/Brand new document.docx'; document.write( str.replace(/\s/g, '') ); 
 var a = "/var/www/site/Brand new document.docx"; alert(a.split(' ').join('')); alert(a.replace( /\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 output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); or var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,""); 

注意:尽pipe您使用“g”或“gi”来删除空格,但它们的行为相同。

如果我们在replace函数中使用'g',它将检查完全匹配。 但如果使用“gi”,则忽略大小写。

供参考点击这里 。

下面的@rsplak回答:实际上,使用split / join方式比使用regexp更快。 查看性能testing用例

所以

var result = text.split(' ').join('')

运行速度比

var result = text.replace(/\s+/g, '')

在小文本中,这是不相关的,但是对于时间很重要的情况,例如在文本分析器中,特别是在与用户交互时,这很重要。


另一方面, \s+处理更广泛的空间字符。 在\n\t ,它也匹配\u00a0字符,那就是什么  在使用textDomNode.nodeValue获取文本时将其textDomNode.nodeValue

所以我认为这里的结论可以做如下:如果你只需要replace空格 ' ' ,使用split / join。 如果可以有符号类的不同符号 – 使用replace(/\s+/g, '')

你可以尝试使用这个:

 input.split(' ').join(''); 

如果要从string的两端(但不在string内部)删除空格,请使用trim()方法,例如

 " abc ".trim() // = "abc" 

备注
您也可以阅读关于trimLeft和trimRight的相关信息 ,从左侧或右侧删除空格,但请注意这两个标准不符合标准,也不在标准轨道上。