Mask US phone number string with JavaScript
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"/>
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);
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">
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">