[英]Javascript Replace - Regular Expression
I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. 我需要替换一个代码示例:OD3-第一个必须始终为字母字符,第二个字母数字,最后一个必须始终为数字。 What's the regular expression
to check and replace
the first and regulate the rest to enter correctly? 检查并replace
第一个并管理其余输入以使其正确输入的regular expression
是什么? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately... 用户可以输入数字0而不是字母O,所以我想立即更正它。
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
这就是我到目前为止所拥有的: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. 首先,我建议仅向用户指示错误,而不要替换这些值。 Something like 就像是
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that: 如果您一定要即时替换价值,则可以执行以下操作:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this. 最好有这样的。
onkeyup="testRegex(this.value)";
It is not .replace()
it is .test()
不是.replace()
它是.test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.