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] 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[0-9]查找0到9之间的任何数字[A-Z]查找从大写字母A到大写字母Z [a-z]的任何字符查找从小写字母a到小写字母z的任何字符
plus underscore
and minus
.
加上下划线和减号。
Therefore, this string is OK:
因此,这个字符串是OK:
Abc054_34-bd
Abc054_34-BD
And this string is bad:
这个字符串很糟糕:
Fš 04//4.
Fš04// 4。
From the bad string I need the disallowed characters removed.
从坏字符串我需要删除不允许的字符。
How do I stack this regex rule?
如何堆叠此正则表达式规则?
2 个解决方案
#1
24
You can use character class with ^
negation:
你可以使用带有^ negation的字符类:
this.value = this.value.replace(/[^a-zA-Z0-9_-]/g,'');
Tests:
测试:
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.
因此,通过在[^ ...]中添加字符,您可以决定应该允许哪些字符以及替换所有其他字符。
#2
2
Try:
尝试:
this.value = this.value.replace(/\w|-/g, '');
Reference:
参考:
- Regular Expressions, at the Mozilla Developer Network.
- Mozilla开发者网络上的正则表达式。
#1
24
You can use character class with ^
negation:
你可以使用带有^ negation的字符类:
this.value = this.value.replace(/[^a-zA-Z0-9_-]/g,'');
Tests:
测试:
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.
因此,通过在[^ ...]中添加字符,您可以决定应该允许哪些字符以及替换所有其他字符。
#2
2
Try:
尝试:
this.value = this.value.replace(/\w|-/g, '');
Reference:
参考:
- Regular Expressions, at the Mozilla Developer Network.
- Mozilla开发者网络上的正则表达式。