-
-
Save AbdulKabia/fc4bcb7b71611f644de506635570e8e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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