Mask US phone number string with JavaScript
Asked Answered
P

9

43

I need regular express for US Phone Number format.I want to replace the phone number string into below US phone number string format in JavaScript.

var number = "4031234789";

And I want to mask it in below format:-

number = number.mask('(000) 000-0000');

Can anyone show me a regular expression for that in JavaScript?

Purificator answered 15/7, 2013 at 9:44 Comment(2)
possible duplicate of How can I mask an HTML input using javacript?Rosales
There are all these answers that people gave you on your other question.Limitless
R
158

This answer assumes you want the following format: (000) 000-0000 (as the OP states).

There are multiple ways to implement this, but here are a couple different approaches:


If you want to simply mask the number on the blur event (when the field loses focus), then you could use the following:

document.getElementById('phone').addEventListener('blur', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
  e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});
<p>Masked on the blur event (remove focus).</p>
<input type="text" id="phone" placeholder="(555) 555-5555"/>

Alternatively, if you would rather mask the number while typing, you can listen to the input event and then conditionally mask the number based on the regex match:

document.getElementById('phone').addEventListener('input', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
<input type="text" id="phone" placeholder="(555) 555-5555"/>
Reformatory answered 29/3, 2015 at 22:0 Comment(5)
This works great! I was able to easily adapt it to mask a foreign zip code.Cushat
Was searching for exactly this kind of simple function. Most were bloated and didn't work well. Woo!Labialize
Doesn't work in compatibility mode on IE11 :( but works beautifully when compatibility mode is offNerissanerita
@josh-crozier It is not working in mobile. Not sure about Android but iphone it is not working.Pyjamas
When we delete typed numbers from mobile, it wont allow after separator symbol.Pyjamas
L
11

You can use regular expression and then concatenate to form your string.

var USNumber = "4031234789".match(/(\d{3})(\d{3})(\d{4})/);
USNumber = "(" + USNumber[1] + ") " + USNumber[2] + "-" + USNumber[3];
console.log(USNumber);
Lunalunacy answered 15/7, 2013 at 9:55 Comment(0)
A
4

For those who want to publish the number of Uzbekistan in JS

  document.getElementById('organization_phone').addEventListener('input', function (e) {
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,2})(\d{0,3})(\d{0,2})(\d{0,2})/);
    e.target.value = '+(' + x[1] + ') ' + x[2] + '-' + x[3] + '-' + x[4] + '-' + x[5];
  });
 <input type="text" id="organization_phone" name="organization_phone"  required placeholder="(+998) 99-000-00-00" value="+998">
Actinoid answered 1/8, 2021 at 9:12 Comment(0)
H
4

      document.getElementById('organization_phone').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = '(' +x[1] + ') '+ x[2] + '-' + x[3]
      });
<input type="text" id="organization_phone" name="organization_phone"  required placeholder="(998) 000-0000">
Herald answered 4/11, 2021 at 11:18 Comment(0)
S
1

I thought I edited a few things to make it match the 555-555-5555 format but I get a javascript error for x[1]. It says Uncaught TypeError: Cannot read properties of null (reading '1') The code still works but being below average user of JS, I'm still learning and I would really like to try and understand what's going on here. Thanks!

 document.getElementById('Main_Phone').addEventListener('input', 
 function (e) 
 {
 var x = e.target.value.replace(/\D/g, '').match(/^(\d{3})(\d{3}). 
 (\d{4})$/);
 e.target.value = (x[1] + '-' + x[2] + '-' + x[3]);     
 });
Sabella answered 15/7, 2013 at 9:44 Comment(0)
E
1

There is my solution

According to wikipedia, the maximum phone number length is 15 digitals

The code below implements the mask +00 (000) 000-00-00-000

Also, the backspace works as well

document.querySelector('[name="phone_number"]')
    .addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '')
            .match(/(\d{0,2})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})(\d{0,3})/);

        if (!x[1]) {
            e.target.value = '+';

            return;
        }

        if (!x[2]) {
            e.target.value = `+${x[1]}`;

            return;
        }

        e.target.value = `+${x[1]} (${x[2]}`
            + ( x[3] ? `) ${x[3]}` : '' )
            + ( x[4] ? `-${x[4]}` : '' )
            + ( x[5] ? `-${x[5]}` : '' )
            + ( x[6] ? `-${x[6]}` : '' );
    });
<input name="phone_number" placeholder="+00 (000) 000-00-00-000">
Enchantment answered 3/7, 2022 at 13:19 Comment(0)
L
0

    document.addEventListener("DOMContentLoaded", () => {
        const input = document.querySelector("#tel-input");

        input.addEventListener('input', (e) => {
            if (e.target.value)
            {
                const x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
                e.target.value =  + x[1] + (x[2] ? `-${x[2]}` : '') + (x[3] ? `-${x[3]}` : '')
            }
        });
    });
<input id="tel-input" type="tel" class="form-control" value="" placeholder="xxx-xxx-xxxx" maxlength="12"/>
Learn answered 12/4, 2022 at 20:29 Comment(0)
H
-1

You can use my package https://github.com/jsonmaur/coverup, which can mask the input string onblur and maintain the symbols in the string.

Heterogamy answered 11/5, 2016 at 20:13 Comment(0)
H
-2

Use phone number masking plugins for that.

Check the following plugins:

Hara answered 15/7, 2013 at 9:47 Comment(1)
The question asked about how to mask a US phone number in javascript, not what libraries there are that already do this.Besprinkle

© 2022 - 2025 — McMap. All rights reserved.