修改Javascript以在插入电话号码时删除不必要的字符

时间:2018-03-27 14:50:21

标签: javascript onclick viber

我使用下面的Javascript来呼叫Viber信使聊天,以获取我粘贴到该字段中的特定电话号码。如何更改它,当插入一个数字,删除不必要的字符:空格,括号,连字符,只留下数字的最后10位数?

       response.xpath('//div[@class="vw_m108_item_container vw_accordion_item_container"]//div[@class="inner"]/div[@class="td"]//text()')

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用基本的JS字符串函数:



(function() { // Do not allow using variables outside script
  var tel = document.getElementById("tel");
  tel.maxLength = 20; // When JS enabled, limit is more than 10
  tel.pattern = ".*"; // When JS enabled, allow everything
  tel.onchange = // After input
  tel.onkeyup = // Key is up (after character written)
  tel.onkeypress = // Character writen (for repeating)
    function () {
      var str = tel.value;
      for (var str_old = null; str !== str_old;) { // Until no changes done
        str_old = str;
        str = str // You can put here more characters or regex
          .replace("-", "") // Multiple similar characters
          .replace("–", "")
          .replace("—", "")
          .replace("/", "")
          .replace(" ", "")
          .replace("(", "")
          .replace(")", "")
          .replace("[", "")
          .replace("]", "")
          .replace("{", "")
          .replace("}", "");
      }
      tel.value = str.substr(-10); // Put it back and use last 10 characters (without '-' means except first 10 characters)
    }
})()

<input type="tel" id="tel" maxlength="10" pattern="[^-–—/ ()[\]{}]+" required  />
<input type="button" id="btn-1" value="Viber" onClick="javascript: window.open('viber://chat?number=%2B38' + document.getElementById('tel').value, '_self');" />
&#13;
&#13;
&#13;