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?
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.
本文标签: javascriptnew RegExp(39d2d1039) doesn39t workStack Overflow
版权声明:本文标题:javascript - new RegExp('^+d{2}.d{10}$') doesn't work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743967336a2570128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论