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

"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兼容正则表达式库吗?

其他回答

对于en-US(美式英语)字符串,这应该足够了:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )

注意,如果你支持UTF-8和像chinese/russian这样的字符,这也会替换它们,所以你真的必须指定你想要什么。

/[^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英语时才会工作。

我遇到过同样的问题,这个解决方案很管用,而且可读性很强:

var sentence = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var newSen = sentence.match(/[^_\W]+/g).join(' ');
console.log(newSen);

结果:

"This is an example of a string with punctuation"

诀窍是创建一个负集合。这意味着它匹配任何不在集合内的东西,即[^abc] -不是a, b或c

\W是任何非单词,所以[^\W]+将否定任何非单词char。

通过添加_(下划线),你也可以否定它。

让它全局应用/g,然后你可以通过它运行任何字符串,并清除标点符号:

/[^_\W]+/g

又漂亮又干净;)

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

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

如果您想从字符串中删除特定的标点符号,最好明确地删除您想要的标点符号,例如

replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"")

执行上述操作仍然不会返回您指定的字符串。如果您想要删除由于删除疯狂的标点符号而留下的任何额外的空格,那么您将需要执行以下操作

replace(/\s{2,}/g," ");

完整的例子:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");

在firebug控制台中运行代码的结果: