1

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.

Stefan Dunn
  • 5,363
  • 7
  • 48
  • 84
  • 1
    `new RegExp("(?:\\+44|0)7\\d{9}", 'g');` – Avinash Raj Mar 18 '15 at 11:22
  • @AvinashRaj, that worked! Can you explain why this is the case? – Stefan Dunn Mar 18 '15 at 11:23
  • 3
    within double quotes, escape all the backslashes one more time or otherwise it would treat backslash as an escape sequence. – Avinash Raj Mar 18 '15 at 11:24
  • @AvinashRaj Within *all* string literals. JavaScript/ECMAScript makes no difference between single- and double-quoted strings, unlike e.g. PHP. And the point is that escape sequences *start* with a backslash both in string literals and `RegExp` initialisers (\\ is the escape sequence for the backslash in both literal types). The string literal is evaluated *before* the string value is passed to the `RegExp` constructor. As the other answer says, when there are no variable parts in the expression, use `RegExp` initialisers instead to avoid such errors and make the expression more readable. – PointedEars Mar 18 '15 at 12:08

1 Answers1

0

You can create RegExp by using short method

var a = /(\+44|0)7\d{9}/g

Its must works good)

Illia Moroz
  • 343
  • 1
  • 2
  • 13