![](/img/trans.png)
[英]Javascript remove all characters from string which are not numbers, letters and whitespace
[英]Remove all characters that are not letters or numbers in a String
我怎样才能删除所有不是字母或'数字'的字符?
我有一个字符串:
var string = 'This - is my 4 String, and i - want remove all characters 49494 that are not letters or "numbers"';
我想转变成这个:
var string = 'This is my 4 String and i want remove all characters 49494 that are not letters or numbers'
这个有可能?
谢谢!!
你可以使用这样的正则表达式:
[\W_]+
我们的想法是匹配\\W
一个非单词字符(那些不是AZ
, az
, 0-9
和_
字符)并且还明确地添加_
(因为下划线被认为是单词字符)
var str = 's - is my 4 String, and i - want remove all characters 49494 that are not letters or "numbers"';
var result = str.replace(/[\W_]+/g, ' ');
我喜欢这样做的方法是使用RegEx。 这将选择所有非计数器和非计数器,并将其替换为空或删除它们:
string = string.replace(/[^\s\dA-Z]/gi, '').replace(/ +/g, ' ');
Explanantion:
[^ NOT any of there
\s space
\d digit
A-Z letter
]
是的,可以使用正则表达式
string = string.replace(/[^a-z0-9]+|\s+/gmi, " ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.