Skip to content

Instantly share code, notes, and snippets.

@AbdulKabia
Last active February 2, 2018 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AbdulKabia/fc4bcb7b71611f644de506635570e8e9 to your computer and use it in GitHub Desktop.
Save AbdulKabia/fc4bcb7b71611f644de506635570e8e9 to your computer and use it in GitHub Desktop.
// Find phone numbers from given array
let findPhoneNumbers = async arrayOfNumbers => {
// Object to hold returned phone numbers
let numbersArray = {
validNumbers: [],
invalidNumbers: []
};
// Filter through the array looking for numbers
for (let i = 0; i < arrayOfNumbers.length; i++) {
let currentNumber;
let numWasFound = true;
try {
currentNumber = phoneUtil.parse(arrayOfNumbers[i], 'CA');
}
catch (error) {
numWasFound = false;
}
if (numWasFound) {
// Format the found phone number into (xxx) xxx-xxxx
let tempNumb = phoneUtil.format(currentNumber, PNF.NATIONAL);
// Note: Google's library will only properly format the number if it is a valid one
// Which is why I do this check and place the number into the correct array
if (tempNumb.includes('(')) {
numbersArray.validNumbers.push(tempNumb);
}
else {
numbersArray.invalidNumbers.push(tempNumb);
}
}
}
return numbersArray;
}
app.get(`/api/phonenumbers/parse/text/:givenText?`, async (request, response) => {
// Check if param was passed
if (request.params.givenText) {
// Replace anything that isn't a number or a comma with nothing
// split into array by splitting on commas
let userData = request.params.givenText.replace(/[^0-9,]/g, '').split(',');
let numbersFound = await findPhoneNumbers(userData);
response.json(numbersFound);
}
else {
response.status(400).json([]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment