Skip to content

Instantly share code, notes, and snippets.

@listochkin
Created September 10, 2013 08:28
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 listochkin/6506537 to your computer and use it in GitHub Desktop.
Save listochkin/6506537 to your computer and use it in GitHub Desktop.
Phone Number formatting with RegExps
// Let's say we have US phone numbers in forms:
// 1222333444 and 2223334444
//
// We need to format them in a form:
// 1-(222)-333-4444
// Step 1: prepend phone number with '1' if it's in a short form:
var phone = '2223334444';
phone = phone.replace(/(\d{10})/g, '1$1');
phone === '12223334444';
// Step 2: split the phone number into chunks
phone = phone.replace(/(\d)(\d{3})(\d{3})(\d{4})/g, '$1-($2)-$3-$4');
phone === '1-(222)-333-4444'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment