javascript - 使用 javascript 和正则表达式添加对电话号码输入扩展的支持
问题描述
我有一个功能可以很好地将电话号码(type="tel")输入屏蔽为用户类型。
但是我想添加支持,以便用户可以在需要时对号码进行扩展,例如 (123) 456-7890 x12345
我不清楚如何编辑我的正则表达式来支持这一点。
(function() {
// finds all phone number inputs
var phoneNumberInputs = document.querySelectorAll('[type=tel]');
// a function that formats the number while typing
function maskPhoneInputs() {
this.addEventListener('input', function(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
}
// to apply the function to each input
phoneNumberInputs.forEach(maskPhoneInputs);
})();
解决方案
弄清楚了。这里是:
function maskPhoneInputExt() {
this.addEventListener('input', function(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})?(\d{0,8})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '') + (x[4] ? ' x' + x[4] : '');
});
}
需要?(\d{0,8})
在 match 方法的末尾添加可选的子表达式。
还添加 + (x[4] ? ' x' + x[4] : '')
到赋值中。
推荐阅读
- javascript - 通过 QiMessaging JavaScript 连接到虚拟机器人
- c# - 在 httplisteners authenticationselectordelegate 中给出拒绝身份验证消息
- arrays - 如何将第二个viewcontroller文本字段值传递给第一个viewcontroller数组并在swift4中点击按钮时关闭
- apache-camel - 如何仅在一段时间内暂停骆驼路线
- android - 以编程方式更改适配器中的布局资源
- android - Google Api 客户端已使用 id 0 进行管理
- javascript - 将变量传递给 Vue js 模态组件
- javascript - 如何将 post/get json 值 (html) 发送到 API?
- ios - 隐藏和检索与 Viber 相同的当前视图控制器
- c# - 在 Active Directory 中按 OU 搜索时未获取所有组