Форматировать номер телефона js

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.

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.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans. There are two approaches to format the numbers which are discussed below: 

    Approach 1:

    • A RegExp is used to replace the original phone number with a human-readable phone number.
    • The RegExp is searching for the 3 digits and saves it in a variable($1 for the first 3 digits, $2 for the second 3 digits, and so on.)
    • In the end, It is just concatenating them with ‘-‘ among them.

    Example: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                phoneNo.replace(/(d{3})(d{3})(d{4})/,

                                '$1-$2-$3');

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    How to format a phone number in Human-Readable using JavaScript ?

    Approach 2:

    • This example is using the substr() method to format a phone number in Human-Readable format.
    • It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.

    Example 2: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                down.innerHTML = phoneNo.substr(0, 3)

                        + '-' + phoneNo.substr(3, 3)

                        + '-' + phoneNo.substr(6, 4);

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    How to format a phone number in Human-Readable using JavaScript ?

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans. There are two approaches to format the numbers which are discussed below: 

    Approach 1:

    • A RegExp is used to replace the original phone number with a human-readable phone number.
    • The RegExp is searching for the 3 digits and saves it in a variable($1 for the first 3 digits, $2 for the second 3 digits, and so on.)
    • In the end, It is just concatenating them with ‘-‘ among them.

    Example: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                phoneNo.replace(/(d{3})(d{3})(d{4})/,

                                '$1-$2-$3');

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    How to format a phone number in Human-Readable using JavaScript ?

    Approach 2:

    • This example is using the substr() method to format a phone number in Human-Readable format.
    • It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.

    Example 2: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                down.innerHTML = phoneNo.substr(0, 3)

                        + '-' + phoneNo.substr(3, 3)

                        + '-' + phoneNo.substr(6, 4);

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    How to format a phone number in Human-Readable using JavaScript ?

    PhoneFormat.js

    A javascript phone formatter

    Install

    via Bower

    bower install phoneformat.js

    via NPM

    npm install phoneformat.js

    All files for usage are in the /dist directory.

    • Amd:
      • phone-format-amd.js or phone-format-amd.min.js
    • Exports:
      • phone-format-exports.js or phone-format-amd.min.js
    • Global:
      • phone-format-global.js or phone-format-global.min.js
    • Original Blend:
      • phone-format.js or phone-format.min.js

    API

    Function Parameters Example
    countryForE164Number phoneNumber : string phoneFormat.countryForE164Number(validInternationalPhoneNumber);
    formatNumberForMobileDialing countryCode : string, phoneNumber : string phoneFormat.formatNumberForMobileDialing(countryCode, validPhoneNumber);
    isValidNumber phoneNumber : string, countryCode : string phoneFormat.isValidNumber(validPhoneNumber, countryCode);
    formatE164 countryCode: string, phoneNumber : string phoneFormat.formatE164(countryCode, validPhoneNumber);
    formatInternational countryCode : string, phoneNumber : string phoneFormat.formatInternational(countryCode, validPhoneNumber);
    formatLocal countryCode : string, phoneNumber : string phoneFormat.formatLocal(countryCode, validPhoneNumber);
    exampleLandlineNumber countryCode : string phoneFormat.exampleLandlineNumber(countryCode);
    exampleMobileNumber countryCode : string phoneFormat.exampleMobileNumber(countryCode);
    cleanPhone phoneNumber : string phoneFormat.cleanPhone(validPhoneNumber);
    countryCodeToName countryCode : string phoneFormat.countryCodeToName(countryCode);

    FAQ

    Is PhoneFormat.js in sync with the latest libphonenumber?

    More often then not PhoneFormat.js will NOT be using the latest version of libphonenumber.

    It was last synced v8.10.6

    If this is causing you any headaches, please follow the instructions below to update the source files in /lib.

    • Step 1

      • Copy to your clipboard, the contents of closure.txt at the top of this page
    • Step 2

      • Go to Googles Closure Compiler Service
    • Step 3

      • Paste the contents of closure.txt into the big textarea on the left side of the screen under the Compile button.
      • Make sure you delete whatever text is already the textarea!
      • After you’ve pasted it press the Compile button
      • If everything works correctly, on the right side of the screen will be a freshly compiled google-libraries.js
    • Step 4

      • Update lib/google-libraries.js with the compiled libraries from the compiler service.
      • Run npm run build
      • Commit your change, push it up and submit a pull request.
      • Thank you!

    Questions?

    • @sturdynut
    • @albeebe

    This project was created by @albeebe.

    Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans. There are two approaches to format the numbers which are discussed below: 

    Approach 1:

    • A RegExp is used to replace the original phone number with a human-readable phone number.
    • The RegExp is searching for the 3 digits and saves it in a variable($1 for the first 3 digits, $2 for the second 3 digits, and so on.)
    • In the end, It is just concatenating them with ‘-‘ among them.

    Example: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                phoneNo.replace(/(d{3})(d{3})(d{4})/,

                                '$1-$2-$3');

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    Approach 2:

    • This example is using the substr() method to format a phone number in Human-Readable format.
    • It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.

    Example 2: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                down.innerHTML = phoneNo.substr(0, 3)

                        + '-' + phoneNo.substr(3, 3)

                        + '-' + phoneNo.substr(6, 4);

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans. There are two approaches to format the numbers which are discussed below: 

    Approach 1:

    • A RegExp is used to replace the original phone number with a human-readable phone number.
    • The RegExp is searching for the 3 digits and saves it in a variable($1 for the first 3 digits, $2 for the second 3 digits, and so on.)
    • In the end, It is just concatenating them with ‘-‘ among them.

    Example: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                phoneNo.replace(/(d{3})(d{3})(d{4})/,

                                '$1-$2-$3');

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    Approach 2:

    • This example is using the substr() method to format a phone number in Human-Readable format.
    • It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.

    Example 2: This example implements the above approach. 

    html

    <script src=

    </script>

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP">

    </p>

    <button onclick="GFG_Fun()">

        click here

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var up = document.getElementById('GFG_UP');

        var down = document.getElementById('GFG_DOWN');

        var phoneNo = '4445556678';

        up.innerHTML = "Click on the button to format "

            + "the phone number.<br>Phone No: " + phoneNo;

        function GFG_Fun() {

            down.innerHTML =

                down.innerHTML = phoneNo.substr(0, 3)

                        + '-' + phoneNo.substr(3, 3)

                        + '-' + phoneNo.substr(6, 4);

        }

    </script>

    Output:

    How to format a phone number in Human-Readable using JavaScript ?

    One of the most common task we face while working is to format the phone number with javascript or Jquery.

    Learn how you can effectively format the phone number in javascript.

    Example

    Input:
    9809142333
    
    Output:
    (980) 914-2333
    

    Format phone number without country code

    To format phone number properly we need to first make sure that the input is numeric and is not more than 10 numbers.

    Now once we have our input ready we can format it in US phone format.

    let formatPhoneNumber = (str) => {
      //Filter only numbers from the input
      let cleaned = ('' + str).replace(/D/g, '');
      
      //Check if the input is of correct length
      let match = cleaned.match(/^(d{3})(d{3})(d{4})$/);
    
      if (match) {
        return '(' + match[1] + ') ' + match[2] + '-' + match[3]
      };
    
      return null
    };
    
    Input:
    console.log(formatPhoneNumber('9809142333'));
    console.log(formatPhoneNumber('98091sss42333'));
    
    Output:
    "(980) 914-2333"
    "(980) 914-2333"
    

    This works great for input without country extension code. But if you want to format phone number with country extension code then we have to modify the function.

    Format phone number with country code

    let formatPhoneNumber = (str) => {
      //Filter only numbers from the input
      let cleaned = ('' + str).replace(/D/g, '');
      
      //Check if the input is of correct
      let match = cleaned.match(/^(1|)?(d{3})(d{3})(d{4})$/);
      
      if (match) {
        //Remove the matched extension code
        //Change this to format for any country code.
        let intlCode = (match[1] ? '+1 ' : '')
        return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
      }
      
      return null;
    }
    
    Input:
    console.log(formatPhoneNumber('9809142333'));
    console.log(formatPhoneNumber('+19801542335'));
    
    Output:
    "(980) 914-2333"
    "+1 (980) 154-2335"
    

    Понравилась статья? Поделить с друзьями:
  • Форматирование номера телефона python
  • Форматирование номера телефона php
  • Формат украинского номера телефона
  • Формат турецкого номера телефона
  • Формат стационарного номера телефона