在一个字符串中移除所有不是字母或数字的字符

7

如何移除所有不是字母或“数字”的字符?

我有一个字符串:

var string = 'This - is my 4 String, and i - want remove all characters 49494 that are not letters or "numbers"';

And i want transform into this:

var string = 'This is my 4 String and i want remove all characters 49494 that are not letters or numbers'

这是可能的吗?谢谢!

string.replace(/[^\w\s]/g, '') - Scott Sauyet
你想在文本中只写数字或数字和字母吗?还是在他们写完后你会将它们删除? - Mohammed Moustafa
只翻译文本内容,不解释。 - user4002542
3个回答

6
您可以使用这样的正则表达式:
[\W_]+

这个想法是使用\W匹配非单词字符(那些不是A-Za-z0-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, ' ');

1
我喜欢使用正则表达式来实现。这将选择所有非字母和非数字,并将它们替换为无或删除它们:
string = string.replace(/[^\s\dA-Z]/gi, '').replace(/ +/g, ' ');

解释:

[^  NOT any of there
  \s  space
  \d  digit
  A-Z letter
]

1

是的,使用正则表达式可以实现。

string = string.replace(/[^a-z0-9]+|\s+/gmi, " ");

1
你能解释一下吗? :B - user4002542

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接