How to format a phone number with jQuery

前端 未结 16 1648
执念已碎
执念已碎 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 05:58

    An alternative solution:

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

    0 讨论(0)
  • 2020-11-28 05:58

    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'
    });
    
    0 讨论(0)
  • 2020-11-28 06:01

    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

    0 讨论(0)
  • 2020-11-28 06:03

    Simple: http://jsfiddle.net/Xxk3F/3/

    $('.phone').text(function(i, text) {
        return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    });
    

    Or: http://jsfiddle.net/Xxk3F/1/

    $('.phone').text(function(i, text) {
        return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
    });
    

    Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.

    0 讨论(0)
  • 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
    <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.

    0 讨论(0)
  • 2020-11-28 06:06

    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;
    });
    
    0 讨论(0)
提交回复
热议问题