I\'m currently displaying phone numbers like 2124771000
. However, I need the number to be formatted in a more human-readable form, for example: 212-477-10
Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.
Quick and dirty example:
$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
var val_old = $(this).val();
var newString = new libphonenumber.asYouType('US').input(val_old);
$(this).focus().val('').val(newString);
}
});
(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)
I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX
$('.class-name').on('keypress', function(e) {
var key = e.charCode || e.keyCode || 0;
var phone = $(this);
if (phone.val().length === 0) {
phone.val(phone.val() + '(');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if (phone.val().length === 4) {
phone.val(phone.val() + ')');
}
if (phone.val().length === 5) {
phone.val(phone.val() + ' ');
}
if (phone.val().length === 9) {
phone.val(phone.val() + '-');
}
if (phone.val().length >= 14) {
phone.val(phone.val().slice(0, 13));
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.on('focus', function() {
phone = $(this);
if (phone.val().length === 0) {
phone.val('(');
} else {
var val = phone.val();
phone.val('').val(val); // Ensure cursor remains at the end
}
})
.on('blur', function() {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Live example: JSFiddle
$(".phoneString").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return text;
});
Output :-(123) 657-8963
Here's a combination of some of these answers. This can be used for input fields. Deals with phone numbers that are 7 and 10 digits long.
// Used to format phone number
function phoneFormatter() {
$('.phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '')
if (number.length == 7) {
number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
$(this).val(number)
});
}
Live example: JSFiddle
I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found. So this answer is for anyone searching for something similar to what I was searching for.