【问题标题】:What would be the best way to ignore characters in a input [duplicate]忽略输入中字符的最佳方法是什么[重复]
【发布时间】:2020-10-08 07:21:51
【问题描述】:

如果我输入he7ck 我希望它忽略任何不是字母的东西,所以它只是将输入作为heck 我该怎么做?

【问题讨论】:

标签: javascript


【解决方案1】:

input.oninput = (e) => e.target.value = e.target.value.replace(/[^a-z\s]+/gi, "");
<input id="input"/>

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来替换您不想要的所有内容 ""。如果您希望它完全禁止用户在输入过程中输入数字,请保持原样。否则,如果您希望它获得他们的全部输入,然后应用限制,请将 input.oninput 函数更改为 input.onchange

    var input = document.getElementById('input');
    
    input.oninput = function() {
      let data = this.value;
      if (data.match(/[0-9]/g)) {
         console.log(data);
         data = data.replace(/[0-9]/g, "");
         this.value = data;
      }
    }
    <input id="input">

    【讨论】:

      【解决方案3】:

      您可以使用如下简单的表达式:

      document.getElementById("myInput").addEventListener("input",function(){
           var str = this.value;
           this.value = str.replace(/[^a-zA-Z\s]+/g, "")
      });
      <input id="myInput"/>

      【讨论】:

      • 我不确定问题中是否有人问过,但这不支持空格
      猜你喜欢
      • 2017-09-03
      • 2020-11-20
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2017-02-27
      • 2023-03-22
      • 2014-09-04
      • 1970-01-01
      相关资源
      最近更新 更多