I'm trying to mask a phone number with javascript in this format +4 (444) 444-44-88
Based on this answer I came up with this solution
document.getElementById('phone').addEventListener('input', function (e) {
let x = e.target.value.replace(/\D/g, '').match(/(\d{1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
e.target.value ='+' + x[1] + '(' + x[2] + ')' + x[3] + '-' + x[4] + '-' + x[5];
});
It works but the problem is that it seems like I can't delete characters from input.
As soon as I hit '-'
backspace doesn't work. But, for example, if I delete every number x[i]
then all the strings '-'
and '()'
can be deleted.