Pawan
Pawan

Reputation: 2218

Mask US phone number string with JavaScript

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?

Upvotes: 44

Views: 137321

Answers (8)

Abram
Abram

Reputation: 41844

I implemented this in a slightly more elegant way where the paranths and dash are added naturally as you type:

document.addEventListener('DOMContentLoaded', (event) => {
    const phoneInput = document.getElementById('phone');

    phoneInput.addEventListener('input', (event) => {
        let input = phoneInput.value;
        let cursorPosition = phoneInput.selectionStart;

        // Remove all non-numeric characters
        let numbersOnly = input.replace(/\D/g, '');

        // Limit to maximum length of 10 digits
        if (numbersOnly.length > 10) {
            numbersOnly = numbersOnly.substring(0, 10);
        }

        // Apply formatting
        let formattedInput = '';
        if (numbersOnly.length > 0) {
            formattedInput += '(' + numbersOnly.substring(0, 3);
            if (numbersOnly.length >= 3) {
                formattedInput += ') ';
            }
        }
        if (numbersOnly.length > 3) {
            formattedInput += numbersOnly.substring(3, 6);
            if (numbersOnly.length >= 6) {
                formattedInput += '-';
            }
        }
        if (numbersOnly.length > 6) {
            formattedInput += numbersOnly.substring(6, 10);
        }

        // Set the formatted value
        phoneInput.value = formattedInput;

        // Adjust cursor position
        const formattedCursorPosition = cursorPosition + (formattedInput.length - input.length);
        phoneInput.setSelectionRange(formattedCursorPosition, formattedCursorPosition);
    });
});
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
}

.container {
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

label {
    display: block;
    margin-bottom: 8px;
}

input {
    width: 200px;
    padding: 8px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 4px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phone Number Input Mask</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <label for="phone">Phone Number:</label>
        <input type="text" id="phone" placeholder="(xxx) xxx-xxxx" maxlength="14">
    </div>

    <script src="script.js"></script>
</body>
</html>

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240858

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"/>

Upvotes: 160

PavloM
PavloM

Reputation: 11

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">

Upvotes: 1

Pax Exterminatus
Pax Exterminatus

Reputation: 550


    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"/>

Upvotes: 0

Ali Raza
Ali Raza

Reputation: 720

      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">

Upvotes: 4

Akbarali
Akbarali

Reputation: 904

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">

Upvotes: 4

Zohaib Ahmed Shakir
Zohaib Ahmed Shakir

Reputation: 115

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

Upvotes: 11

Related Questions