Skip to content

Instantly share code, notes, and snippets.

@aradnom
Last active March 24, 2017 22:04
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 aradnom/9ba83971a14ca3953ccb45af54e70f62 to your computer and use it in GitHub Desktop.
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.
/**
* 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