Oleksandr Khavdiy Oleksandr Khavdiy - 3 months ago 13
Javascript Question

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

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 this?
Thanks

Answer

If you want to include the minus sign "-" in the character class, you have to put it into the end of range:

val.replace(/[^a-zA-Z_0-9-]/g, '')