Backspace \b 在包含在JS中的字母正则表达式中不起作用。

huangapple go评论68阅读模式
英文:

Backspace \b not working when included in alphabetic regex in JS

问题

以下代码块会过滤掉所有非字母字符和退格键(\b),但你可以看到退格键不起作用,也被过滤掉了。为什么会这样?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    $('#field').keydown(function(e) {
      if (!/^[A-Za-z\b]$/i.test(e.key)) {
        e.preventDefault();
      }
    });

<!-- language: lang-html -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <input type="text" id="field" />

<!-- end snippet -->
英文:

The following blocks out all chars which are not either alphabetic or backspace (\b), but you can see that the Backspace doesn't work and is also filtered out. Why is that?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

$(&#39;#field&#39;).keydown(function(e) {
  if (!/^[A-Za-z\b]$/i.test(e.key)) {
    e.preventDefault();
  }
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;

&lt;input type=&quot;text&quot; id=&quot;field&quot; /&gt;

<!-- end snippet -->

答案1

得分: 1

The event.key value for the backspace key is "Backspace".

$('#field').keydown(function(e) {
  if (!/^([a-z]|Backspace)$/i.test(e.key)) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field" />
英文:

The event.key value for the backspace key is &quot;Backspace&quot;.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

$(&#39;#field&#39;).keydown(function(e) {
  if (!/^([a-z]|Backspace)$/i.test(e.key)) {
    e.preventDefault();
  }
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;

&lt;input type=&quot;text&quot; id=&quot;field&quot; /&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月14日 04:09:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定