如何使用正则表达式在JavaScript中从字符串中去除所有标点符号?
如何使用正则表达式在JavaScript中从字符串中去除所有标点符号?
如果我有一个包含任何类型非字母数字字符的字符串:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"
如何在JavaScript中获取无标点符号的版本:
"This is an example of a string with punctuation"
admin 更改状态以发布 2023年5月24日
如果你想从字符串中去除特定的标点符号,最好是明确地去除你要的内容,例如:
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控制台中运行代码的结果: