Matthis.h
Matthis.h

Reputation: 909

invalid regex javascript

Can you explain me why this regex is invalid ?

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

Validate by regex online

Upvotes: 0

Views: 68

Answers (2)

Dez
Dez

Reputation: 5838

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'));

Upvotes: 1

David784
David784

Reputation: 7464

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.

Upvotes: 3

Related Questions