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

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

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

"This is an example of a string with punctuation"

当前回答

如果您正在使用lodash

_.words('This, is : my - test,line:').join(' ')

这个例子

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

其他回答

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

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

如果您正在使用lodash

_.words('This, is : my - test,line:').join(' ')

这个例子

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

删除除字母数字字符和空白之外的所有内容,然后将多个相邻空白折叠为单个空格。

详细解释:

\w是任意数字、字母或下划线。 \s是任何空白。 [^\w\s\']是指任何不是数字、字母、空格、下划线或单引号的字符。 [^\w\s\']|_与#3相同,只是加了下划线。

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

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

又漂亮又干净;)

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

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

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