0

Can you explain me why this regex is invalid ?

new RegExp("^(0|\+33)+[0-9]{9}$");

Validate by regex online

3
  • escape + character Commented Jul 2, 2019 at 21:30
  • No, work with this site Commented Jul 2, 2019 at 21:32
  • with regex online you don't have to worry about the string escapes in addition to regex escapes. That's why it works with regex online but not in this example, because you're constructing the RegExp with a string. As @MarkMeyer said, if you use a regex literal you won't run into the string escape problem. Commented Jul 2, 2019 at 21:34

2 Answers 2

3

You need a double backslash before the first +, like this:

new RegExp("^(0|\\+33)+[0-9]{9}$");

When JavaScript evaluates the string, it reads \+ as simply +. Then the RegExp sees |+, which is two Regex operators back to back (or and repeat 1 to infinite times)...which is invalid.

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

5 Comments

You forgot the double backslash.
@GetOffMyLawn thanks, I got in too much of a hurry. Fixed now
Invalid regular expression: /^(0|+33)+[0-9]{9}$/: Nothing to repeat
@Matthis.h not sure what browser you're using, but I just copied and pasted my code into Chrome/75.0.3770.90 console, and it worked perfectly. Returned this: /^(0|\+33)+[0-9]{9}$/
I'm using Chrome 75.0.3770.100
1

Your regex work as expected with regex literals. With the string literals you need to double escape the special chars.

const r = /^(0|\+33)+[0-9]{9}$/;
console.log(r.test('0782896736'));
console.log(r.test('+33782896736'));
console.log(r.test('blabla'));


const regexp = new RegExp('^(0|\\+33)+[0-9]{9}$');
console.log(regexp.test('0782896736'));
console.log(regexp.test('+33782896736'));
console.log(regexp.test('blabla'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.