简体   繁体   English

正则表达式电话屏蔽

[英]Regex phone masking

I'm trying to write phone input masking function.我正在尝试编写电话输入屏蔽 function。 Here it is:这里是:

 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,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 />

It works, but with one problem.它有效,但有一个问题。 When I press the backspace key, I erase the phone number to something like +1 (111).当我按下退格键时,我会将电话号码删除为 +1 (111) 之类的内容。 Such an entry is valid for the regular expression, and the string is replaced by itself这样的条目对正则表达式有效,字符串被自己替换

Per @ggorlen's suggestion in the comments, here is one way to do this:根据@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,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 />

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

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