0

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?

1
  • learn to use regex101.com before coming and asking, it will save you and everyone else a bunch of time. Commented May 2, 2016 at 18:45

4 Answers 4

4

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;

Sign up to request clarification or add additional context in comments.

Comments

0

var res=phoneNumber.match(/38[0-9]{8,10}/m);

phone number length allowed :10-12

Comments

0

Your regex is wrong, if you want to match 38xxxxxxxxxx you should remove [] brackets because this means 3 or 8 and afterwards it tries to match 10 digits, so just remove the []

var re=new RegExp("^38\d{10}$");

Comments

0

When using the constructor function, the normal string escape rules are necessary.

new RegExp("^38\\d{10}$");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.