如果我有一个字符串,其中有任何类型的非字母数字字符:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"

我如何在JavaScript中得到一个没有标点符号的版本:

"This is an example of a string with punctuation"

当前回答

在支持Unicode的语言中,Unicode Punctuation字符属性是\p{p}——为了便于阅读,通常可以缩写为\pP,有时也可以扩展为\p{Punctuation}。

您正在使用Perl兼容正则表达式库吗?

其他回答

它很简单,只是替换字符而不是单词:

.replace(/[^\w]/g, ' ')

在支持Unicode的语言中,Unicode Punctuation字符属性是\p{p}——为了便于阅读,通常可以缩写为\pP,有时也可以扩展为\p{Punctuation}。

您正在使用Perl兼容正则表达式库吗?

/[^A-Za-z0-9\s]/g应该匹配所有的标点符号,但要保留空格。 因此,如果需要的话,可以使用.replace(/\s{2,}/g, " ")替换额外的空格。您可以在http://rubular.com/中测试正则表达式

.replace(/[^A-Za-z0-9\s]/g,"").replace(/\s{2,}/g, " ")

更新:只有当输入是ANSI英语时才会工作。

如果你想只保留字母和空格,你可以这样做:

str.replace(/[^a-zA-Z ]+/g, '').replace('/ {2,}/',' ')

这取决于你想要返回什么。我最近用了这个:

return text.match(/[a-z]/i);