Last active
April 1, 2019 12:21
-
-
Save johnmurch/3596bfff4a1274b98d8425380f777622 to your computer and use it in GitHub Desktop.
Phone Number Sanitize and Print Friendly
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
var phone = '2125551212'; | |
// make 10 digit phone number pretty | |
phone = phone.replace(/[^\d]+/g, '') | |
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3'); | |
// (212) 555 - 1212 | |
console.log(phone); | |
var inputPhone = "(212) 555 - 1212"; | |
var cleanPhone = inputPhone.replace(/\D/g,''); | |
// 2125551212 | |
console.log(cleanPhone); | |
// functional approach | |
function formatPhoneNumber(phoneNumberString) { | |
var cleaned = ('' + phoneNumberString).replace(/\D/g, '') | |
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/) | |
if (match) { | |
return '(' + match[1] + ') ' + match[2] + '-' + match[3] | |
} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment