即使是 false 也满足条件

condition is met even when is false

我正在尝试检查输入值是否为字母数字。根据 regex101.com,我的正则表达式应该可以工作。但是所有的测试结果都在"incorrect"。

我做错了什么?

var alphaNumeric = /^[a-z0-9]+$/gi;
var input = "123"; //page.input.getValue().toUpperCase();

console.log(input);

if (input.length == 3) {

  if (alphaNumeric.test(input)) {
    console.log("correct");
  } else {
    console.log("incorrect");
  }
} else {

}

摆脱全局标志(无论如何你都在匹配开始和结束)

var alphaNumeric = /^[a-z0-9]+$/i;
console.log(alphaNumeric.test("aaa")); // true
console.log(alphaNumeric.test("AAA")); // true
console.log(alphaNumeric.test("123")); // true
console.log(alphaNumeric.test("a1a1a1")); // true
console.log(alphaNumeric.test("ABC-123")); // false

参见@bobince的回答:

You're using a g (global) RegExp. In JavaScript, global regexen have state: you call them (with exec, test etc.) the first time, you get the first match in a given string. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string. You can also write regex.lastIndex= 0 to reset this state.

(This is of course an absolutely terrible piece of design, guaranteed to confuse and cause weird errors. Welcome to JavaScript!)

You can omit the g from your RegExp, since you're only testing for one match.

所以在你的情况下,每次尝试都会有不同的结果:

    var alphaNumeric = /^[a-z0-9]+$/gi;
    var input = "123";
    console.log(input);
    if (input.length == 3) {
        for (var i=0; i<5; i++){
            if (alphaNumeric.test(input)) {
                console.log("correct");
            } else {
                console.log("incorrect");
            }
        }

    } else {
        
    }