I'm using the following JavaScript code to create a regular expression to match a UK mobile number:
new RegExp("(\+44|0)7\d{9}", 'g'); However, I get an error in the console log saying:
Uncaught SyntaxError: Invalid regular expression: /(?:+44|0)7d{9}/: Nothing to repeat
Similar questions on StackOverflow point to a missing escaped character, but mine seem to be fine.
I have also tried without the global flag.
Help would be greatly appreciated.
new RegExp("(?:\\+44|0)7\\d{9}", 'g');RegExpinitialisers (\\ is the escape sequence for the backslash in both literal types). The string literal is evaluated before the string value is passed to theRegExpconstructor. As the other answer says, when there are no variable parts in the expression, useRegExpinitialisers instead to avoid such errors and make the expression more readable.