如果我有一个字符串,其中有任何类型的非字母数字字符:
"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"
当前回答
这取决于你想要返回什么。我最近用了这个:
return text.match(/[a-z]/i);
其他回答
它很简单,只是替换字符而不是单词:
.replace(/[^\w]/g, ' ')
如果您正在使用lodash
_.words('This, is : my - test,line:').join(' ')
这个例子
_.words('"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"').join(' ')
截至2021年,许多现代浏览器都支持JavaScript内置的:RegExp: Unicode属性转义。所以你现在可以简单地使用\p{p}:
str.replace(/[\p{P}$+<=>^`|~]/gu, '')
如果您想忽略所有符号(\p{S})和标点符号,则可以进一步简化正则表达式。
str.replace(str.replace(/[\p{P}\p{S}]/gu, '')
如果你想剥离除字母(\p{L}),数字(\p{N})和分隔符(\p{Z})之外的所有内容。你可以使用像这样的否定字符集(也适用于非英语字母数字字符):
str.replace(/[^\p{L}\p{N}\p{Z}]/gu, '')
上面的正则表达式可以工作,但更常见的用例是使用正则表达式的空白类而不是Unicode分隔符字符集,因为后者不包括制表符和换行符。试试这个:
str.replace(/[^\p{L}\p{N}\s]/gu, '')
const str = 'This。, -/ is #!$ % ^ & *示例;:{}= -_字符串,带有' ~)()标点符号'; console.log (str。替换(/ [\ p {p }$+<=>^`|~]/ 顾,”); console.log (str。替换(/ [\ p {p} \ p{年代}]/顾”); console.log (str。替换(/ [^ \ p {L} \ p {N} \ p {Z}] /顾”); console.log (str。替换(/ [^ \ p {L} \ p {N} \ s] /顾”);
你也可能喜欢用.replace(/ +/g, ' ')来串起连续的空格。
你可以随意摆弄这些东西!裁判: Unicode字符属性-维基百科 Unicode属性转义- MDN
如果您想从字符串中删除特定的标点符号,最好明确地删除您想要的标点符号,例如
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控制台中运行代码的结果:
根据维基百科的标点符号列表,我必须构建以下正则表达式来检测标点:
[\.’'\[\](){} ⟨⟩:,، 、‒–—―...!.‹›«»‐\-?‘’“”'";/⁄·\&*@\•^†‡°”¡¿※# −№÷׺ª%‰+ =‱¶′″‴§~_|‖¦© ℗®℠™¤₳฿₵¢₡₢₫美元₯֏₠€ƒ₣₲₴₭₺₾ℳ₥₦₧₱₰£៛₽₹₨₪৳₸₮₩¥]