How to Mask a US Phone Number String with JavaScript?

Sometimes, we want to mask a US phone number string with JavaScript.

In this article, we’ll look at how to Mask a US phone number string with JavaScript.

Mask a US Phone Number String with JavaScript

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.

For instance, we write:

<input type="text" id="phone" placeholder="(555) 555-5555" />

to add the input.

Then we write:

document.getElementById('phone').addEventListener('blur', (e) => {
  const x = e.target.value.replace(/D/g, '').match(/(d{3})(d{3})(d{4})/);
  e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});

to select the phone input with document.getElementById('phone').

Then we call addEventListener with 'blur' to listen to the blur event.

The blur event is emitted when we move focus out of the input.

In the event handler, we call replace on the input value to replace all non digit substrings with empty strings.

Then we call match to match the digit groups of a phone number.

Then we set the e.target.value to the phone number with the parentheses and dashes.

x has the digit groups.

Now when we type in a phone number, we should see the parentheses and dashes added to the groups.

Conclusion

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.