如何使用正则表达式在JavaScript中从字符串中去除所有标点符号?

23 浏览
0 Comments

如何使用正则表达式在JavaScript中从字符串中去除所有标点符号?

如果我有一个包含任何类型非字母数字字符的字符串:

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

如何在JavaScript中获取无标点符号的版本:

"This is an example of a string with punctuation"

admin 更改状态以发布 2023年5月24日
0
0 Comments

str = str.replace(/[^\w\s\']|_/g, "")
         .replace(/\s+/g, " ");

移除除了字母数字和空白字符之外的所有内容,然后将多个相邻的空格合并为一个空格。

详细解释:

  1. \w 表示任何数字、字母或下划线。
  2. \s 表示任何空格字符。
  3. [^\w\s\'] 表示除了数字、字母、空格、下划线或单引号之外的任何字符。
  4. [^\w\s\']|_ 表示与 #3 相同,只是加入了下划线。
0
0 Comments

如果你想从字符串中去除特定的标点符号,最好是明确地去除你要的内容,例如:

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控制台中运行代码的结果:

alt text

0