How to format a phone number with jQuery

前端 未结 16 1724
执念已碎
执念已碎 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

    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'
    });
    

提交回复
热议问题