[英]use replace to remove chars not existing in a regex match
我正在尝试允许使用 javascript 正则表达式的单个 html 输入框的以下模式
我使用这个 function 删除任何不匹配的东西
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
这是行不通的。 其他例子是:
我想我遗漏了一些东西..任何建议将不胜感激..
我更改了您的正则表达式并使其更加模块化并且运行良好。
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
你可以试试这个正则表达式
^(0).*|^(-?)([1-9]\d*)?.*|^.*
输入后替换为$1$2$3
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
它有三个测试:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
简而言之:
-
, 0-9
。0
,则之后将不允许输入任何内容。1-9
,则后面只允许输入数字。-
,则接下来只允许输入1-9
,然后输入任何数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.