Skip to content

Instantly share code, notes, and snippets.

@royce002
Created August 21, 2017 18:46
Show Gist options
  • Save royce002/8a21c933bf57f4fddc1e9dc1c753902a to your computer and use it in GitHub Desktop.
Save royce002/8a21c933bf57f4fddc1e9dc1c753902a to your computer and use it in GitHub Desktop.
JS Phone Number Formatter
/*** PHONE NUMBER FORMATTER ***/
function phoneFormat(input) {
// Strip all characters except digits
input = input.replace(/\D/g, '');
// Trim input to ten characters, to preserve phone format
input = input.substring(0, 10);
// Format string based on length
var size = input.length;
if (size == 0) {
input = input;
} else if (size < 3) {
input = '(' + input;
} else if (size < 6) {
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6);
} else {
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + '-' + input.substring(6, 10);
}
return input;
}
// KEY BINDING
document.getElementById('eventContactPhone').addEventListener('keyup', function(evt) {
var phoneNumber = document.getElementById('eventContactPhone');
var charCode = (evt.which) ? evt.which : evt.keyCode;
phoneNumber.value = phoneFormat(phoneNumber.value);
});
//Before Submit document.getElementById('eventContactPhone').value.replace(/\D/g,'');
/*** PHONE NUMBER FORMATTER ***/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment