Return the index of each string that contain a Phone Number? (Javascript)

Viewed 100

I am trying to return the index of each string that contain a Phone Number.

var array = [
  'Just a Call Away, call 314-867-5309 ',
  'The Current city population is 3,443,940,573.',
  'My number is (123) 456-7890',
];

Expected Output: [0,2]

This is what I got so far, I used phoneRe as my regex. I can't seem to figure out how to filter out the string with 3,443,940,573 in my solution below.


function phoneNumber(p){
  var numArray = [];
  var phoneRe = /^[1-9]\d{2}[1-9]\d{2}\d{4}$/;
      
  for (var i = 0; i <p.length; i++){
    
    if (phoneRe.test(p[i].replace(/\D/g, ""))===true){
      numArray.push(i);
    }
}
  return numArray;
}

console.log(phoneNumber(array));
 

 
2 Answers
  var phoneRe = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?/img;

This regex should work better.

You have two issues. Your Regex is not as comprehensive as it could be. There are many phone number matching regexes available online. There are more than a few options in the StackOverflow Thread: Regular expression to match standard 10 digit phone number

The second issue is that you strip all non-numeric characters from your string phoneRe.test(p[i].replace(/\D/g, "")) which is an issue when the formatting of numbers is important to determining if your candidate is a phone number or not.

Use search instead to see if the pattern is present in your string.

var array = [
    'Just a Call Away, call 314-867-5309 ',
    'The Current city population is 3,443,940,573.',
    'My number is (123) 456-7890',
];

function phoneNumber(p) {
    var numArray = [];
    var phoneRe = /(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/g;

    for (var i = 0; i < p.length; i++) {
        if (p[i].search(phoneRe) !== -1) {
            numArray.push(i);
        }
    }
    return numArray;
}

console.log(phoneNumber(array));

If you wanted some more modern JavaScript Syntax

const phoneRe = /(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/g;
const phoneNumber = (numberStrings) => {
    return numberStrings.reduce((accumulator, current, index) => {
        if (current.search(phoneRe) !== -1) {
            accumulator.push(index);
        }
        return accumulator;
    }, []);
};

let strings = [
    'Just a Call Away, call 314-867-5309 ',
    'The Current city population is 3,443,940,573.',
    'My number is (123) 456-7890',
];

console.log(phoneNumber(strings));
Related