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.

4
  • 1
    new RegExp("(?:\\+44|0)7\\d{9}", 'g'); Commented Mar 18, 2015 at 11:22
  • @AvinashRaj, that worked! Can you explain why this is the case? Commented Mar 18, 2015 at 11:23
  • 3
    within double quotes, escape all the backslashes one more time or otherwise it would treat backslash as an escape sequence. Commented Mar 18, 2015 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. Commented Mar 18, 2015 at 12:08

1 Answer 1

0

You can create RegExp by using short method

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

Its must works good)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.