Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
Pawan Avatar asked Jul 15 '13 09:07

Pawan


People also ask

How do I mask a phone number?

The FCC mandated that all carriers in the United States make it possible for users to be able to block their number from appearing on caller IDs. So, to mask your phone number straight from your phone, follow these steps: Enter *67 before the entire number, then press the call button.

What is masking in Javascript?

The JavaScript Input Mask or masked textbox is a control that provides an easy and reliable way to collect user input based on a standard mask. It allows you to capture phone numbers, date values, credit card numbers, and other standard format values.

What is a number mask?

Number Masking is an advanced data protection measure designed to ensure the privacy of both the support agent and the caller. It allows two on-call entities to communicate without disclosing their phone numbers. The purpose of number masking is to ensure the security of customer interactions.


2 Answers

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

There are multiple different 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"/>
like image 69
Josh Crozier Avatar answered Sep 20 '22 12:09

Josh Crozier


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);
like image 26
Zohaib Ahmed Shakir Avatar answered Sep 19 '22 12:09

Zohaib Ahmed Shakir