javascript 使用javascript删除字符串中的所有非字母数字和任何空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24062281/
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
Remove all non alphanumeric and any white spaces in string using javascript
提问by BaconJuice
I'm trying to remove any non alphanumeric characters ANY white spaces from a string.
我正在尝试从字符串中删除任何非字母数字字符任何空格。
Currently I have a two step solution and would like to make it in to one.
目前我有一个两步解决方案,并希望将其合二为一。
var name_parsed = name.replace(/[^0-9a-zA-Z ]/g, ''); // Bacon, Juice | 234
name_parsed = name_parsed.replace(/ /g,'')
console.log(name_parsed); //BaconJuice234
Could someone let me know how to achieve above in one execution and not two?
有人可以让我知道如何在一次执行而不是两次执行中实现上述目标吗?
回答by VisioN
Remove the space from the first set and will do the job:
从第一组中删除空间并完成工作:
name.replace(/[^0-9a-zA-Z]/g, '');
You may read this code as "remove all characters that are not digits ([0-9]
) and alpha characters ([a-zA-Z]
)".
您可以将此代码读作“删除所有不是数字 ( [0-9]
) 和字母字符 ( [a-zA-Z]
) 的字符”。
Alternatively, you can use the i flag to make your regular expression ignore case. Then the code can be simplified:
或者,您可以使用 i 标志使您的正则表达式忽略大小写。那么代码可以简化:
name.replace(/[^0-9a-z]/gi, '');