Skip to content

Instantly share code, notes, and snippets.

@webinista
Created April 7, 2014 02:43
Show Gist options
  • Save webinista/10014145 to your computer and use it in GitHub Desktop.
Save webinista/10014145 to your computer and use it in GitHub Desktop.
Format a numeric string as xxx-xxx-xxxx
function formatUSPhoneNumber(number) {
var x = 0, groups = [], len, num;
/* Force string conversion */
num = number+'';
/* Remove non numeric characters */
num = num.replace(/\D/g,'');
if(num.length !== 10){
throw new Error('The argument passed needs to contain 10 digits.')
return;
}
len = num.length;
num = num.split('').reverse();
while( x < len/3){
groups[x] = num.splice(-3,3).reverse().join('');
x++;
}
if( groups.length > 3 ){
groups[2] = groups[2].concat( groups.splice( 3 - groups.length, 1 ) );
}
return groups.join('-');
}
@mdshahedali
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment