Last active
March 24, 2017 22:04
-
-
Save aradnom/9ba83971a14ca3953ccb45af54e70f62 to your computer and use it in GitHub Desktop.
Parse phone number components from a string, string manipulation flavor. Tends to be more bulletproof than regex flavor.
This file contains hidden or 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
/** | |
* Given a raw phone number, parse out individual components. | |
* | |
* @param {String} raw Raw phone number to parse | |
* | |
* @return {Object} Returns object containing countryCode, areaCode, officeCode | |
* and stationNumber components | |
*/ | |
function getPhoneNumberComponents ( raw ) { | |
// First cut raw string down to just numbers | |
let numbers = raw | |
.replace( /\s/g, '' ) | |
.split( '' ) | |
.filter( ( char ) => { return ! isNaN( +char ); }); | |
// If length of numbers is < 7, it's not a valid number | |
if ( numbers.length < 7 ) { return null; } | |
// Then split into prefix (country/area code) and suffix | |
let suffix = numbers.splice( numbers.length - 7, 7 ); | |
let prefix = numbers; | |
// Deal with prefix | |
let areaCode = prefix.splice( prefix.length - 3, 3 ); | |
let countryCode = prefix; | |
// Split suffix into office code/station number | |
let officeCode = suffix.splice( 0, 3 ); | |
let stationNumber = suffix; | |
// And shoot back combined results | |
return { | |
countryCode: countryCode.join( '' ), | |
areaCode: areaCode.join( '' ), | |
officeCode: officeCode.join( '' ), | |
stationNumber: stationNumber.join( '' ) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment