Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 338
Oleksandr IY Avatar asked Aug 27 '12 13:08

Oleksandr IY


3 Answers

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, '')
like image 196
Dmitry Avatar answered Sep 23 '22 12:09

Dmitry


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.

like image 27
pimvdb Avatar answered Sep 22 '22 12:09

pimvdb


I would prefer this regex:

val.replace(/[^\w-]+/gi, "");
like image 36
sQVe Avatar answered Sep 20 '22 12:09

sQVe