See the answer of @bobince:
https://stackoverflow.com/a/2630538/1241218
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.
So in your case you will have different results on every try:
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 {
}