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));