首页 > 解决方案 > 使用 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);

})();

标签: javascript

解决方案


弄清楚了。这里是:

  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] : '')到赋值中。


推荐阅读