Phone 屏蔽函数在表单字段中插入额外的 "x's"

Phone masking function inserting extra "x's" in form field

我的 phone 屏蔽脚本插入了正确的破折号,但对于带有扩展名的数字,它会在第 12 个字符后添加额外的 "x's"。我正在尝试格式化掩码,使其看起来像 000-0000x0000000,但它正在返回 000-000-0000xxxx0000。知道我做错了什么吗?

$(document).ready(function() { 
 var phoneNumber = $('#phone_number');
 
 // Adds a phone number mask
   phoneNumber.on('input paste', function(e) {
  var phoneNumStr = e.target.value.split("-").join("");

  // Create a new string with the hyphen
  pro = phoneNumStr.split('').map(function(str, index) {
  
   // Inserts a hyphen after the third and sixth characters
   if (index == 3 || index == 6) {
    return "-" + str;
   } else if (index == 10) {
    return "x" + str;
   } else {
    return str;
   }
  }).join('');
  
  // Returns the new string
  $(this).val(pro);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="phone_number">Phone Number*</label> 
<input type="text" id="phone_number" name="phone_number" maxlength="20">

更改您的拆分“-”以使用正则表达式拆分破折号和 x 以从评估的字符串中删除 x。

$(document).ready(function() { 
 var phoneNumber = $('#phone_number');
 
 // Adds a phone number mask
   phoneNumber.on('input paste', function(e) {
                                         //remove dash and x
  var phoneNumStr = e.target.value.split(/[x-]/).join("");

  // Create a new string with the hyphen
  pro = phoneNumStr.split('').map(function(str, index) {
  
   // Inserts a hyphen after the third and sixth characters
   if (index == 3 || index == 6) {
    return "-" + str;
   } else if (index == 10) {
    return "x" + str;
   } else {
    return str;
   }
  }).join('');
  
  // Returns the new string
  $(this).val(pro);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="phone_number">Phone Number*</label> 
   <input type="text" id="phone_number" name="phone_number" maxlength="20">

试试下面的代码

$(document).ready(function() {  
var phoneNumber = $('#phone_number');

// Adds a phone number mask
phoneNumber.on('input paste', function(e) {
    var phoneNumStr = e.target.value.split("-").join("");

    // Create a new string with the hyphen
    pro = phoneNumStr.split('').map(function(str, index) {

        // Inserts a hyphen after the third and sixth characters
        if (index == 3 || index == 6) {
            return "-" + str;
        } else if (index == 10) {
            if(str.indexOf("x")==-1)
              return "x" + str;
            else {
              return str;
            }
        } else {
            return str;
        }
    }).join('');

    // Returns the new string
    $(this).val(pro);
});

});