admin管理员组

文章数量:1355581

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?

Share Improve this question asked Oct 5, 2011 at 10:49 Saeed NeamatiSaeed Neamati 35.9k41 gold badges139 silver badges192 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

You 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.

本文标签: javascriptnew RegExp(39d2d1039) doesn39t workStack Overflow