[英]use replace to remove chars not existing in a regex match
I'am trying to allow following pattern for a single html input box with javascript regex我正在尝试允许使用 javascript 正则表达式的单个 html 输入框的以下模式
I use this function the remove anything that doesn't match it我使用这个 function 删除任何不匹配的东西
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.这是行不通的。 Other examples is:其他例子是:
I think I'am missing something.. Any suggestions would be most appreciated..我想我遗漏了一些东西..任何建议将不胜感激..
I changed your regexp and made it a bit more modular and it worked fine.我更改了您的正则表达式并使其更加模块化并且运行良好。
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()));
});
You may try this regex你可以试试这个正则表达式
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3
after input输入后替换为$1$2$3
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:它有三个测试:
^(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
In short:简而言之:
-
, 0-9
are allowed.通常只允许-
, 0-9
。0
first, nothing will be allowed after.如果您先输入0
,则之后将不允许输入任何内容。1-9
first, only numbers are allowed after.如果您先输入1-9
,则后面只允许输入数字。-
first, only 1-9
is allowed next, then any digit is allowed after.如果您先输入-
,则接下来只允许输入1-9
,然后输入任何数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.