如何从 JavaScript 中的字符串中删除空白字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3893625/
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 would I remove blank characters from a string in JavaScript?
提问by Nisanio
How would I remove blank characters from a string in JavaScript?
如何从 JavaScript 中的字符串中删除空白字符?
A trim is very easy, but I don't know how to remove them from insidethe string. For example:
修剪很容易,但我不知道如何将它们从字符串内部移除。例如:
222 334 -> 222334
222 334 -> 222334
采纳答案by Jay
Nick Craver has a good response, if you're OK with regex, go for it.
Nick Craver 有一个很好的回应,如果你对正则表达式没问题,那就去做吧。
I just want to add that you can do this without Regex as well. You can just use a normal JavaScript replace(), using the parameters (" ", "") to replace all whitespace with empty strings.
我只想补充一点,您也可以在没有 Regex 的情况下执行此操作。您可以使用普通的 JavaScript replace(),使用参数 (" ", "") 将所有空格替换为空字符串。
Update: Whoops, this won't work with multiple whitespaces.
更新:糟糕,这不适用于多个空格。
回答by Nick Craver
You can use a regex, like this to replace all whitespace:
您可以使用正则表达式,像这样替换所有空格:
var oldString = "222 334";
var newString = oldString.replace(/\s+/g,"");
Or for literally justspaces:
或者实际上只是空格:
var newString = oldString.replace(/ /g,"");
回答by kennebec
You can also do this without a regular expression or a replace-
您也可以在没有正则表达式或替换的情况下执行此操作
var string= string.split(' ').join('');