1

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.

jsfiddle

Person
  • 2,190
  • 7
  • 30
  • 58

1 Answers1

0

The reason why backspace is not working is that when you hit backspace, it actually deletes "-" but then your event listener again reassign the value to input box and it looks as if backspace is not working at all.

Here is a messy but working solution to your problem :

document.getElementById('phone').addEventListener('input', function (e) {
  let hasUnclosedParanthesis = !e.target.value.match(/\)/g) && e.target.value.match(/\(/g);
  //alert(e.target.value, hasUnclosedParanthesis);
  let x = e.target.value.replace(/\D/g, '').match(/(\d{1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
  let pn = '+';
  if(x[1]) {
  pn += x[1];
  }
  if(x[2] && !hasUnclosedParanthesis) {
  pn += '(' + x[2] + ')';
  }
  if(x[2] && hasUnclosedParanthesis) {
  pn += '(' + x[2].substring(0, x[2].length-1) + ')';
  }
  if(x[3]) {
  pn += x[3];
  }
  if(x[4]) {
  pn += '-' + x[4];
  }
  if(x[5]) {
  pn += x[5];
  }
  e.target.value = pn;
});
binariedMe
  • 4,309
  • 1
  • 18
  • 34
  • Thank you. I will try to implement that. – Person Nov 12 '17 at 13:39
  • In original answer I think it works based on conditional expression `e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '')` – Person Nov 12 '17 at 13:49
  • Yes, you can write the same if conditions with ternary operators... both will do the same. This just was required because you had this opening/closing bracket... that needed special condition – binariedMe Nov 12 '17 at 13:52