如何删除所有不是字母的字符或'数字' ??
我有一个字符串:
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'
这可能吗?
谢谢!
答案 0 :(得分:2)
你可以使用这样的正则表达式:
[\W_]+
我们的想法是与\W
非单词字符(不是A-Z
,a-z
,0-9
和_
的字符)匹配明确添加_
(因为下划线被认为是单词字符)
<强> Working demo 强>
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, ' ');
答案 1 :(得分:0)
我喜欢这样做的方式是使用RegEx。这将选择所有非 -let和非 -numbers并将其替换为空或删除它们:
string = string.replace(/[^\s\dA-Z]/gi, '').replace(/ +/g, ' ');
Explanantion:
[^ NOT any of there
\s space
\d digit
A-Z letter
]
答案 2 :(得分:0)
是的,可以使用正则表达式
string = string.replace(/[^a-z0-9]+|\s+/gmi, " ");