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

I need to replace all characters that do not match the range a-zA-Z_-0-9 . So I am doing val.replace(/[^a-zA-Z_-0-9]/g, '') but I get an error. How can I bite this? Thanks

+7
source share
8 answers

If you want to include the minus sign “-” in the character class, you must put it at the end of the range:

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

I would prefer this regex:

 val.replace(/[^\w-]+/gi, ""); 
+5
source

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

In your case, just run away from it: \- . This is parsed as a - symbol.

+3
source

You have a bad range, delete - between _ and a range of numbers, and put it at the end or the beginning.

+2
source

try the following:

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

You need to avoid the "-"

 val.replace(/[^a-zA-Z_\-0-9]/g, '') 
+2
source
 $(this).val($(this).val().replace(/[^a-zA-Z_0-9-]/g, '')); 
0
source

All Articles