简体   繁体   English

使用javascript屏蔽电话号码,删除字符

[英]Masking a phone number with javascript, deleting characters

I'm trying to mask a phone number with javascript in this format +4 (444) 444-44-88 我正在尝试使用javascript屏蔽此格式的电话号码+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. 但是,例如,如果我删除每个数字x[i]则可以删除所有字符串'-''()'

jsfiddle jsfiddle

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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM