I want check phone numbers. Right format is 38xxxxxxxxxx.
My check:
var phoneNumber=document.getElementById('phone').value;
var re=new RegExp("^[38]\d{10}$");
var res=phoneNumber.match(re);
I always get null. What's wrong?
When using the RegExp constructor function with quotes, normal string escape rules apply. Thus, you need to escape the special character \\d
as \\\\d
. Also you need to change [38]
to simply 38
, as [38]
matches 3
or 8
.
var str = '381234567890'; var re = new RegExp("^38\\\\d{10}$"); // or new RegExp(/^38\\d{10}$/); without quotes // or re = /^38\\d{10}$/; var res = str.match(re); document.body.innerHTML = "Match result: " + res;
var res=phoneNumber.match(/38[0-9]{8,10}/m);
phone number length allowed :10-12
您的正则表达式是错误的,如果要匹配38xxxxxxxxxx
,则应删除[]
括号,因为这表示3
或8
,然后它会尝试匹配10位数字,因此只需删除[]
var re=new RegExp("^38\d{10}$");
使用构造函数时,必须使用常规的字符串转义规则。
new RegExp("^38\\d{10}$");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.