如何使用 JavaScript 从字符串中删除空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5963182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove spaces from a string using JavaScript?
提问by JLuiz
How to remove spaces in a string? For instance:
如何删除字符串中的空格?例如:
Input:
输入:
'/var/www/site/Brand new document.docx'
Output:
输出:
'/var/www/site/Brandnewdocument.docx'
回答by ?ime Vidas
This?
这个?
str = str.replace(/\s/g, '');
Example
例子
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );
Update:Based on this question, this:
更新:基于这个问题,这个:
str = str.replace(/\s+/g, '');
is a better solution. It produces the same result, but it does it faster.
是更好的解决方案。它产生相同的结果,但速度更快。
The Regex
正则表达式
\s
is the regex for "whitespace", and g
is the "global" flag, meaning match ALL \s
(whitespaces).
\s
是“空白”的正则表达式,g
是“全局”标志,表示匹配所有\s
(空白)。
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.
作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空格替换为任何其他字符串。
回答by rsplak
var a = b = " /var/www/site/Brand new document.docx ";
console.log( a.split(' ').join('') );
console.log( b.replace( /\s/g, '') );
Two ways of doing this!
有两种方法可以做到!
回答by Kamil Kie?czewski
SHORTEST and FASTEST: str.replace(/ /g, '');
最短和最快:str.replace(/ /g, '');
Benchmark:
基准:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
这是我的结果 - Chrome 67.0.3396(64 位)、Safari 11.0.3(13604.5.6)、Firefox 59.0.2(64 位)上的(2018.07.13)MacOs High Sierra 10.13.3:
SHORT strings
短字符串
Short string similar to examples from OP question
类似于 OP 问题示例的短字符串
The fastest solution on all browsers is / /g
(regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join
solution. Change to
\s
or add +
or i
to regexp slows down processing.
所有浏览器上最快的解决方案是/ /g
(regexp1a) - Chrome 17.7M(操作/秒)、Safari 10.1M、Firefox 8.8M。所有浏览器中最慢的是split-join
解决方案。更改到
\s
或添加+
或i
以正则表达式减慢处理。
LONG strings
长字符串
For string about ~3 milion character results are:
对于大约 300 万个字符的字符串,结果是:
- regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
- regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
- split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,
- regexp1a:Safari 50.14 操作/秒,Firefox 18.57,Chrome 8.95
- regexp2b:Safari 38.39、Firefox 19.45、Chrome 9.26
- 拆分连接:Firefox 26.41、Safari 23.10、Chrome 7.98、
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
你可以在你的机器上运行它:https: //jsperf.com/remove-string-spaces/1
回答by Minstel
Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case
按照@rsplak 的回答:实际上,使用拆分/连接方式比使用正则表达式要快。查看性能测试用例
So
所以
var result = text.split(' ').join('')
var result = text.split(' ').join('')
operates faster than
运行速度比
var result = text.replace(/\s+/g, '')
var result = text.replace(/\s+/g, '')
On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.
对于小文本,这无关紧要,但对于时间很重要的情况,例如在文本分析器中,尤其是在与用户交互时,这很重要。
On the other hand, \s+
handles wider variety of space characters. Among with \n
and \t
, it also matches \u00a0
character, and that is what
is turned in, when getting text using textDomNode.nodeValue
.
另一方面,\s+
处理更广泛的空格字符。在\n
and 中\t
,它还匹配\u00a0
字符,这就是
使用textDomNode.nodeValue
.
So I think that conclusion in here can be made as follows: if you only need to replace spaces' '
, use split/join. If there can be different symbols of symbol class- use replace(/\s+/g, '')
所以我认为这里的结论可以如下:如果你只需要替换空格' '
,使用split/join。如果可以有不同的符号类符号- 使用replace(/\s+/g, '')
回答by Muhammad Tahir
var input = '/var/www/site/Brand new document.docx';
//remove space
input = input.replace(/\s/g, '');
//make string lower
input = input.toLowerCase();
alert(input);
回答by Raveendra007
var output = '/var/www/site/Brand new document.docx'.replace(/ /g, "");
or
var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");
Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.
注意:尽管您使用 'g' 或 'gi' 来删除空格,但两者的行为相同。
If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.
如果我们在替换函数中使用 'g',它将检查完全匹配。但是如果我们使用“gi”,它会忽略大小写敏感。
for reference click here.
参考点击这里。
回答by SoEzPz
Regex + Replace()
正则表达式 + 替换()
Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.
尽管正则表达式可能会更慢,但在许多用例中,开发人员一次只处理几个字符串,因此考虑速度无关紧要。尽管 / / 比 /\s/ 快,但使用 '\s' 可能更清楚地向其他开发人员解释正在发生的事情。
let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'
Split() + Join()
拆分() + 加入()
Using Split + Join allows for further chained manipulation of the string.
使用 Split + Join 允许对字符串进行进一步的链式操作。
let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";
回答by Eric Xue
Although there are ways to use regex to remove spaces, there is a simple function that can remove all whitespace called .trim();
:
虽然有一些方法可以使用正则表达式来删除空格,但有一个简单的函数可以删除所有名为 的空格.trim();
:
var str = "abr a cadab ra";
str = str.trim();
//str = "abracadabra"