【问题标题】:How to remove special character from a string in input on onkeyup event [duplicate]如何在onkeyup事件的输入中从字符串中删除特殊字符[重复]
【发布时间】:2020-07-19 05:39:01
【问题描述】:

我正在尝试删除特殊字符,如 @、# 等,除了带有空字符串的空格

<input type='text' onkeyup="this.value.replace('/[^a-zA-Z0-9]/g', '')">

但它不起作用

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您需要删除正则表达式模式周围的quotes,并将替换值分配给this.value,因为replace 方法会创建一个新字符串,它不会修改您正在操作的字符串

    <input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g, '')">

    【讨论】:

    • 是的,它正在工作,谢谢
    【解决方案2】:

    以这种方式更改值不会替换原始值。它给你一个新的字符串。完成替换后,您必须将其分配回this.value,这样就可以了。

    此外,正则表达式模式不需要用引号引起来。它以“/”开头和结尾。所以你必须删除它。

    更多阅读 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    <input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g,'')">

    建议

    内联事件侦听器被认为是不好的做法,您可能应该在 JS 领域使用 addEventListener 这样做。

    【讨论】:

      【解决方案3】:

      使用内联事件处理程序通常是not a good idea。替代方案:使用 input 事件和委托处理程序:

      {
        document.addEventListener("input", textOnly, true);
        
        function textOnly(evt) {
          const origin = evt.target;
          if (origin.id === "textOnly") {
            origin.value = origin.value
              .replace(/[^a-z0-9]$/i, "");
            //                   ^ only the last inputted character
          }
        }
      }
      <input type="text" id="textOnly">

      【讨论】:

        猜你喜欢
        • 2014-05-20
        • 2020-11-19
        • 2019-12-22
        • 2012-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        相关资源
        最近更新 更多