How do I replace special characters with regex in javascript?

后端 未结 2 1797
醉酒成梦
醉酒成梦 2021-02-12 23:19

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

2条回答
  •  离开以前
    2021-02-12 23:48

    You can use character class with ^ 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.

提交回复
热议问题