val.replace(/[^a-zA-Z_-0-9]/g, '') produce SyntaxError: invalid range in character class

前端 未结 8 1315
失恋的感觉
失恋的感觉 2020-12-11 03:35

I need to replace all chars which are not match with range a-zA-Z_-0-9. So I do val.replace(/[^a-zA-Z_-0-9]/g, \'\') but get error. How can I bit t

相关标签:
8条回答
  • 2020-12-11 04:35

    You expect that - character to be parsed as being literal, but it is in fact parsed as a range: _-0 means _ to 0, just like a-z means a to z. However, since _ has a higher character code than 0, you get an error.

    In your case, just escape it: \-. This is parsed as the - character.

    0 讨论(0)
  • 2020-12-11 04:35

    You need to escape the "-"

    val.replace(/[^a-zA-Z_\-0-9]/g, '')
    
    0 讨论(0)
提交回复
热议问题