[javascript] How to format a phone number with jQuery

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-1000. Here's my current HTML:

<p class="phone">2124771000</p>

This question is related to javascript jquery

The answer is


Don't forget to ensure you are working with purely integers.

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

Following event handler should do the needful:

$('[name=mobilePhone]').on('keyup', function(e){
                    var enteredNumberStr=this.$('[name=mobilePhone]').val(),                    
                      //Filter only numbers from the input
                      cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
                      inputLength=cleanedStr.length,
                      formattedNumber=cleanedStr;                     
                                      
                      if(inputLength>3 && inputLength<7) {
                        formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
                      }else if (inputLength>=7 && inputLength<10) {
                          formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                          
                      }else if(inputLength>=10) {
                          formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                        
                      }
                      console.log(formattedNumber);
                      this.$('[name=mobilePhone]').val(formattedNumber);
            });

An alternative solution:

_x000D_
_x000D_
function numberWithSpaces(value, pattern) {_x000D_
  var i = 0,_x000D_
    phone = value.toString();_x000D_
  return pattern.replace(/#/g, _ => phone[i++]);_x000D_
}_x000D_
_x000D_
console.log(numberWithSpaces('2124771000', '###-###-####'));
_x000D_
_x000D_
_x000D_


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


I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.

Problem

I would like my phone number html input field to auto-format (mask) the value as the user types.

Solution

Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.

Formatting a phone number is as easy as:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

 $(".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.


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.)


try something like this..

jQuery.validator.addMethod("phoneValidate", function(number, element) {
    number = number.replace(/\s+/g, ""); 
    return this.optional(element) || number.length > 9 &&
        number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

$("#myform").validate({
  rules: {
    field: {
      required: true,
      phoneValidate: true
    }
  }
});

Input:

4546644645

Code:

PhoneNumber = Input.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "($1)$2-$3");

OutPut:

(454)664-4645

Quick roll your own code:

Here is a solution modified from Cruz Nunez's solution above.

// 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{0,3})(\d{0,3})/, "($1) $2");
    } else if (number.length <= 10) {
    number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
    } else {
    // ignore additional digits
    number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);

JSFiddle

  • In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)

  • It requires the zip code for a 10-digit US phone number to be entered.

  • Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.

  • I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:

Recommend jQuery Mask Plugin

I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:

CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

WordPress Contact Form 7: use Masks Form Fields plugin

If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.

Example usage on a Contact Form 7 form:

<label> Your Phone Number (required)
    [tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>

The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.


To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.

    $('#phone').on('input', function() {
      var number = $(this).val().replace(/[^\d]/g, '');
      if (number.length == 3) {
        number = number.replace(/(\d{3})/, "$1-");
      } else if (number.length == 4) {
        number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
      } else if (number.length == 5) {
        number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
      } else if (number.length == 6) {
        number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
      } else if (number.length == 7) {
        number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
      } else if (number.length == 8) {
        number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
      } else if (number.length == 9) {
        number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
      } else if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
      } else if (number.length == 11) {
        number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      } else if (number.length == 12) {
        number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      }
      $(this).val(number);
    });

Use a library to handle phone number. Libphonenumber by Google is your best bet.

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

I recommend to use this package by seegno.


may be this will help

var countryCode = +91;
var phone=1234567890;
phone=phone.split('').reverse().join('');//0987654321
var formatPhone=phone.substring(0,4)+'-';//0987-
phone=phone.replace(phone.substring(0,4),'');//654321
while(phone.length>0){
formatPhone=formatPhone+phone.substring(0,3)+'-';
phone=phone.replace(phone.substring(0,3),'');
}
formatPhone=countryCode+formatPhone.split('').reverse().join('');

you will get +91-123-456-7890


var phone = '2124771000',
    formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)