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

查看:129
本文介绍了如何使用正则表达式从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天全站免登陆