[英]Phone number input mask in JS
I'm trying to figure out where the number 1
comes from (in the example below you write any phone number and press Backspace many times).我试图找出数字
1
来源(在下面的示例中,您可以输入任何电话号码并多次按 Backspace)。 Can you please tell me what is wrong in this code?你能告诉我这段代码有什么问题吗?
const input = document.querySelector('input[name="phone"]'); input.addEventListener('input', function () { let x = input.value; x = x.replace(/^\\+1 /, ''); x = x.replace(/\\D/g, '').match(/(\\d{0,3})(\\d{0,3})(\\d{0,2})(\\d{0,2})/); x = !x[2] ? x[1] : x[1] + ' ' + x[2] + (x[3] ? `-${x[3]}` : '') + (x[4] ? `-${x[4]}` : ''); x = x.startsWith('+1 ') ? x : '+1 ' + x; input.value = x; });
<input name="phone" placeholder="Phone number">
You need remove it on your code.您需要在代码中删除它。
phone = phone.replace(/^\+1 /, '')
Also:还:
phone = phone.startsWith('+1 ') ? phone : '+1 ' + phone;
You had to replace the line:您必须替换该行:
x = x.replace(/^\+1 /, '');
to:到:
x = x.replace(/^\+1/, '');
(remove the space) (去掉空格)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.