Nastya Gorobets Nastya Gorobets - 5 months ago 9x
Javascript Question

RegExp in JavaScript is returning null

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;