且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在javascript中使用正则表达式替换特殊字符?

更新时间:2022-11-11 22:26:44

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

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.