如果我有一个字符串,其中有任何类型的非字母数字字符:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"
我如何在JavaScript中得到一个没有标点符号的版本:
"This is an example of a string with punctuation"
如果我有一个字符串,其中有任何类型的非字母数字字符:
"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(' ')
其他回答
对于en-US(美式英语)字符串,这应该足够了:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )
注意,如果你支持UTF-8和像chinese/russian这样的字符,这也会替换它们,所以你真的必须指定你想要什么。
它很简单,只是替换字符而不是单词:
.replace(/[^\w]/g, ' ')
在支持Unicode的语言中,Unicode Punctuation字符属性是\p{p}——为了便于阅读,通常可以缩写为\pP,有时也可以扩展为\p{Punctuation}。
您正在使用Perl兼容正则表达式库吗?
这取决于你想要返回什么。我最近用了这个:
return text.match(/[a-z]/i);
如果你的目标是一个现代浏览器(不是IE),你可以使用unicode字符类。当您还需要支持诸如德语Umlaute (äöü)或其他字符时,这尤其有用。
这是我最后得到的。它替换所有不是字母、撇号或空格的内容,并用一个空格删除行中的多个空格。
const textStripped = text
.replace(/[’]/g, "'") // replace ’ with '
.replace(/[^\p{Letter}\p{Mark}\s']/gu, "") // remove everything that is not a letter, mark, space or '
.replace(/\s+/g, " ") // remove multiple spaces
.replace(/[’]/g, "'")
First将'(印刷撇号)替换为'(打字机撇号)。因为两者都可以用在像"don 't "这样的词中
.replace(/[^\p{Letter}\p{Mark}\s']/gu, "")
\p{Letter}代表unicode中被归类为字母的任何字符。
\p{Mark}类别需要包括进一步的封面字母标记组合。例如,德语ä可以编码为单个字符,也可以编码为“a”和“Mark”的组合。当从pdf中复制德语文本时,这种情况经常发生。
来源: https://dev.to/tillsanders/let-s-stop-using-a-za-z-4a0m