英文:
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 -->
$('#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 -->
答案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 "Backspace"
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('#field').keydown(function(e) {
if (!/^([a-z]|Backspace)$/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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论