如何使用 JavaScript 从字符串中删除空格? [英] How to remove spaces from a string using JavaScript?
本文介绍了如何使用 JavaScript 从字符串中删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何去除字符串中的空格?例如:
How to remove spaces in a string? For instance:
输入:
'/var/www/site/Brand new document.docx'
输出:
'/var/www/site/Brandnewdocument.docx'
推荐答案
This?
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, '');
是更好的解决方案.它产生相同的结果,但速度更快.
is a better solution. It produces the same result, but it does it faster.
正则表达式
s
是空格"的正则表达式,g
是全局"标志,表示匹配所有 s
(空格).
s
is the regex for "whitespace", and g
is the "global" flag, meaning match ALL s
(whitespaces).
可以找到对 +
的一个很好的解释 这里.
A great explanation for +
can be found here.
作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空格替换为任何其他字符串.
As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.
这篇关于如何使用 JavaScript 从字符串中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文