I want to test a string's format. This string should start with a +
sign, then 2 digits, then a .
sign, then 10 digits.
/^\+\d{2}\.\d{10}$/.test('+34.2398320186');
This way, it works (you can test it). But when I use RegExp
, it says that the syntax has invalid quantifier error. What's wrong?
I want to test a string's format. This string should start with a +
sign, then 2 digits, then a .
sign, then 10 digits.
/^\+\d{2}\.\d{10}$/.test('+34.2398320186');
This way, it works (you can test it). But when I use RegExp
, it says that the syntax has invalid quantifier error. What's wrong?
3 Answers
Reset to default 9You have to escape the \
with a second \\
new RegExp('^\\+\\d{2}\\.\\d{10}$'); // should work
I'll add a remendation from http://www.regular-expressions.info/javascript.html
I remend that you do not use the RegExp constructor with a literal string, because in literal strings, backslashes must be escaped.
Since you're specifying the regex as a string, you also need to escape the '\', because that's also the string escape character. So you'd want:
new RegExp('^\\+\\d{2}\\.\\d{10}$');
You can try this if you don't want to escape backslash
var regex = /^\+\d{2}\.\d{10}$/
new RegExp(regex).test('+34.2398320186');
If you want to use string as param to RegExp then you have to escape the backslash.