我是正则表达式
的新手。我正在寻找/搜索仅允许数字之间有一个连字符的限制。我找到了正则表达式的示例公式,但我不知道为什么下面的代码仍然接受字符。
我想要实现的是
输出
1-1
类似的东西。
$('#txt').keypress(function () {
const exp = /^\d{1,2}(-\d{1,2})?$/;
const el = $(this);
if (exp.test(el.val()) == true)
alert("a");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
最佳答案
您的正则表达式没问题,但您不应该使用 keypress
事件作为触发器,它总是在实际输入任何内容之前触发。使用 .on('input', ...)
代替:
$('#txt').on('input', function () {
const exp = /^\d{1,2}(-\d{1,2})?$/;
const el = $(this);
// replace anything that is not a number or hyphan
el.val(el.val().replace(/[^\d-]|(?<=^|-.*)-|(?<=\d{2,})\d/g, ''));
if (exp.test(el.val()) == true)
console.log("a");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
关于javascript - 仅允许数字和数字之间的单个连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64797145/