修改 Javascript 以在插入 phone 数字时删除不需要的字符

Modifying Javascript for deleting unnecessary characters while inserting a phone number

我使用下面的 Javascript 调用 Viber Messenger 聊天,获取我粘贴到字段中的特定 phone 号码。如何更改插入数字时删除不需要的字符:空格,括号,连字符,只保留数字的最后10位?

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

谢谢。

您可以使用基本的 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');" />