如何使用正则表达式从 JavaScript 中的字符串中删除所有标点符号? [英] How can I strip all punctuation from a string in JavaScript using regex?

查看:49
本文介绍了如何使用正则表达式从 JavaScript 中的字符串中删除所有标点符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a string with any type of non-alphanumeric character in it:

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

我如何在 JavaScript 中获得它的无标点版本:

How would I get a no-punctuation version of it in JavaScript:

"This is an example of a string with punctuation"

推荐答案

如果您想从字符串中删除特定的标点符号,最好明确删除您想要的内容

If you want to remove specific punctuation from a string, it will probably be best to explicitly remove exactly what you want like

replace(/[.,/#!$%^&*;:{}=-_`~()]/g,"")

执行上述操作仍然不会返回您指定的字符串.如果您想删除因删除疯狂标点符号而留下的任何额外空格,那么您将想要做类似

Doing the above still doesn't return the string as you have specified it. If you want to remove any extra spaces that were left over from removing crazy punctuation, then you are going to want to do something like

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

这篇关于如何使用正则表达式从 JavaScript 中的字符串中删除所有标点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆