微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式电话屏蔽

如何解决正则表达式电话屏蔽

我正在尝试编写电话输入屏蔽功能在这里

let input = document.querySelector('input');

input.addEventListener('input',()=>{
    let x = event.target.value.replace(/\D/g,'').match(/(\d{0,1})(\d{0,3})(\d{0,2})(\d{0,2})/);
    event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input />

它有效,但是有一个问题。当我按退格键时,我会将电话号码擦除为+1(111)。这样的条目对正则表达式有效,并且字符串被其自身替换

解决方法

按照@ggorlen在评论中的建议,这是一种实现方法:

let input = document.querySelector('input');

input.addEventListener('keydown',(event)=>{
    if (event.key === "Backspace" || event.key === "Delete") return;
    let x = event.target.value.replace(/\D/g,'').match(/(\d{0,1})(\d{0,3})(\d{0,2})(\d{0,2})/);
    event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input maxlength=18 />

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。