Last active
October 24, 2023 16:13
-
-
Save jamesdaily/829dd2a8e6cad17f3e0d2d1d4829fdc5 to your computer and use it in GitHub Desktop.
phonePartsUSA.js JavaScript function to split a US phone number into its component parts
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
function phonePartsUSA(phoneNumberInput) { | |
const phoneNumber = ("" + phoneNumberInput).replace(/[^0-9]/g, ""); | |
if (phoneNumber.length != 10) throw new Error("phoneNumberInput must have 10 digits"); | |
const areacode = phoneNumber.slice(0, 3); | |
const prefix = phoneNumber.slice(3, 6); | |
const exchange = phoneNumber.slice(6, 10); | |
const dialnumber = prefix + exchange; | |
const dashFormatted = [areacode, prefix, exchange].join('-'); | |
const parensDashFormatted = "(" + areacode + ") " + prefix + "-" + exchange; | |
const parensDashFormattedNoSpace = "(" + areacode + ")" + prefix + "-" + exchange; | |
const phoneNumberObject = { | |
areacode: areacode, | |
prefix: prefix, | |
exchange: exchange, | |
dialnumber: dialnumber, | |
formatted: { | |
dashes: dashFormatted, | |
parensSpaceDash: parensDashFormatted, | |
parensDash: parensDashFormattedNoSpace, | |
numbersOnly: areacode + prefix + exchange | |
} | |
} | |
return phoneNumberObject; | |
} | |
console.log(phonePartsUSA("(123) 456-7890").areacode) | |
// "123" | |
console.log(phonePartsUSA(1234567890).dialnumber) | |
// "4567890" | |
console.log(phonePartsUSA("123.456.7890").formatted.parensSpaceDash) | |
// "(123) 456-7890" | |
console.log(phonePartsUSA("(123) 456-7890").formatted.numbersOnly) | |
// "1234567890" | |
console.log(phonePartsUSA("(123) 456-7890")) | |
// {object} | |
console.log(phonePartsUSA("123456")) | |
// error: "phoneNumberInput must have 10 digits" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment