Created
September 10, 2013 08:28
-
-
Save listochkin/6506537 to your computer and use it in GitHub Desktop.
Phone Number formatting with RegExps
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
// 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