Dheeraj Agrawal Dheeraj Agrawal - 2 months ago 14
Javascript Question

Regex to fetch phone number from string

I want regex which finds out continues max 12 digits long number by ignoring space, plus (+), parenthesis & dash, e.g:

Primary contact number +91 98333332343 call me on this
My number is +91-983 333 32343
2nd number +1 (983) 333 32343, call me
Another one 983-333-32343
One more +91(983)-333-32343 that's all
121 street pin code 421 728 & number is 9833636363


Currently, I have a regex, which does the job of fetching contact numbers from string:

/* This only work for the first case not for any other
and for last one it outputs "121" */

\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+


So what can be done here to support all the above cases, in short ignoring special characters and length should range from 10-12.

Answer

I see that there are numbers ranging from 10 to 13 digits.

You may use

/(?:[-+() ]*\d){10,13}/g

See the regex demo.

Details:

  • (?:[-+() ]*\d){10,13} - match 10 to 13 sequences of:
    • [-+() ]* - zero or more characters that are either -, +, (, ), or a space
    • \d - a digit

var re = /(?:[-+() ]*\d){10,13}/gm; 
var str = 'Primary contact number +91 98333332343 call me on this\nMy number is +91-983 333 32343\n2nd number +1 (983) 333 32343, call me\nAnother one 983-333-32343\nOne more +91(983)-333-32343 that\'s all\n121 street pin code 421 728 & number is 9833636363';
var res = str.match(re).map(function(s){return s.trim();});
console.log(res);