mattz330
mattz330

Reputation: 59

Uncaught SyntaxError: Invalid regular expression: Nothing to repeat

Here is my regex:

var newRegexp= new RegExp('\[\/\[\]\^\$\|\*\+\(\)\\~@#%&\-_+=\{}£<>]{1,}', 'g');

I get the Uncaught SyntaxError: Invalid regular expression: Nothing to repeat error with it, and I can't figure out why. I used it on RegExr and it works fine. Any help is appreciated.

Upvotes: 1

Views: 3123

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You have an escaped first [ that is supposed to start a range. Unescape it.

Also mind that it is better to use a literal notation (I also suggest removing unnecessary escaping as it makes the regex too unreadable):

var newRegexp = /[\/\[\]^$|*+()\\~@#%&_+={}£<>-]+/g;

See demo

Also note that I replaced {1,} with + as it is shorter and means absolutely the same. If we put the hyphen at the end of the character class, we do not have to escape it.

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

You need to double escape the \ like, also inside [] there is no need escape most of the regex special characters

new RegExp('[/\\[\\]^$|*+()~@#%&\\-_+={}£<>]{1,}', 'g');

Upvotes: 1

Related Questions