最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - new RegExp('^+d{2}.d{10}$') doesn't work - Stack Overflow

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论