regex - Mask US phone number string with JavaScript -


i need regular express phone number format.i want replace phone number string below phone number string format in javascript.

var number = "4031234789"; 

and want mask in below format:-

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

can show me regular expression in javascript?

this answer assumes want following format: (000) 000-0000 (as op states).

there multiple different ways implement this, here couple different approaches:


if want mask number on blur event (when field loses focus), use 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 blur event (remove focus).</p>  <input type="text" id="phone" placeholder="(555) 555-5555"/>


alternatively, if rather mask number while typing, can listen input event , conditionally mask number based on 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"/>


Comments