如何在javascript中使用正则表达式替换特殊字符? [英] How do I replace special characters with regex in javascript?

查看:104
本文介绍了如何在javascript中使用正则表达式替换特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要替换字符串中的特殊字符,如下所示:

I need to replace special characters from a string, like this:

this.value = this.value.replace(/\n/g,'');

除正则表达式部分外,我需要它来寻找相反所有这些:

Except for the regex part, I need it to look for the opposite of all these:


[0-9]查找0到9之间的任何数字

[AZ]查找任何从大写字母A到大写字母Z的字符

[az]查找从小写字母a到小写字母z的任何字符

[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z

plus 下划线减去

因此,这个字符串是好的:

Therefore, this string is OK:


Abc054_34-bd

Abc054_34-bd

这个字符串很糟糕:


Fš04// 4.

Fš 04//4.

从坏字符串中我需要删除不允许的字符。

From the bad string I need the disallowed characters removed.

如何堆叠此正则表达式规则?

How do I stack this regex rule?

推荐答案

你可以使用 ^ 否定字符类:

You can use character class with ^ negation:

this.value = this.value.replace(/[^a-zA-Z0-9_-]/g,'');

测试:

console.log('Abc054_34-bd'.replace(/[^a-zA-Z0-9_-]/g,'')); // Abc054_34-bd
console.log('Fš 04//4.'.replace(/[^a-zA-Z0-9_-]/g,'')); // F044

所以把字符放在 [^ ...] ,您可以决定应该允许哪些字符以及所有其他字符替换。

So by putting characters in [^...], you can decide which characters should be allowed and all others replaced.

这篇关于如何在javascript中使用正则表达式替换特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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