How do I replace special characters with regex in javascript?

后端 未结 2 1798
醉酒成梦
醉酒成梦 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:26

    Try:

    this.value = this.value.replace(/\w|-/g, '');
    

    Reference:

    • Regular Expressions, at the Mozilla Developer Network.
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题