简体   繁体   中英

Regular expression to extract a 10 digit mobile number from string in javascript

I wish to validate if my input argument is a 10 digit phone number, even if there is additional text in the input.

I have tried this:

numbemail("my numberis 0987654321") 
function numbemail(data){
var input =data;  
var numb = new RegExp(
   "\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s\\-.]?\\d{2,})+", "g"
);
var numbresult = input.match(numb);
if(numbresult){
   var re=[]
   if(numbresult[0].length === 10){
      re.push(numbresult[0])
   } else if(numbresult[0].length < 10) {  
      re.push(numbresult[0]+" ==>(WrongNumber: you provided Number is less than 10 digits)</p>")
   } else if(numbresult[0].length > 10) { 
      re.push(numbresult[0]+" ==> (WrongNumber: you provided Number is more than 10 digits)</p>")
   }
   console.log(re)
   } 
}

When I tried this expecting 10 digits, but I got numbresult[0].length= 11

If I used a 10 digit string, then numbresult[0].length= 10

Expected Input:

input = ("my mobile number is 9087654321")

Expected Output:

"9087654321"

Try this one

 var regex = /[\\+]?\\d{10}/ let strings = ['my numberis 0987654321', 'my number 8 is 9087654321', 'my number 8 is 9087654321123', 'my number 8 is 9087654'] strings.forEach(str => { let output = str.match(regex) if(output){ console.log('number is valid', output[0]) return } console.log('number is not valid - kindly enter 10 digit mobile number', output) })

Try to make your RegExp more simple. You write too complex code for simple task.

let input = "my numberis 0987654321";
// filter symbols which can separate phone number dights
input = input.split(" ").join("").split("-").join("");
let phoneNumber = input.match(/\d{10,}/)[0];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM