Skip to content

Instantly share code, notes, and snippets.

@johnmurch
Last active April 1, 2019 12:21
Show Gist options
  • Save johnmurch/3596bfff4a1274b98d8425380f777622 to your computer and use it in GitHub Desktop.
Save johnmurch/3596bfff4a1274b98d8425380f777622 to your computer and use it in GitHub Desktop.
Phone Number Sanitize and Print Friendly
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