How to format a phone number with jQuery

前端 未结 16 1718
执念已碎
执念已碎 2020-11-28 05:13

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

16条回答
  •  春和景丽
    2020-11-28 06:04

    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:

    • https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/
    • http://www.igorescobar.com/blog/2012/05/06/masks-with-jquery-mask-plugin/
    • http://www.igorescobar.com/blog/2013/04/30/using-jquery-mask-plugin-with-zepto-js/

    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

    or

    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:

    
    

    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.

提交回复
热议问题