How to format a phone number with jQuery

前端 未结 16 1720
执念已碎
执念已碎 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条回答
  •  Happy的楠姐
    2020-11-28 06:12

    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.

提交回复
热议问题