const emailRegex = /^\w+@\w+\.\w+$/gi;
function isValid(email) {
return emailRegex.test(email);
}
console.log(isValid('a@b.com'));
console.log(isValid('a@b.com'));const emailRegex = /^\w+@\w+\.\w+$/i;
function isValid(email) {
return emailRegex.test(email);
}
console.log(isValid('a@b.com'));
console.log(isValid('a@b.com'));Bug: With the g flag, regex.test() advances lastIndex after a match. The next call starts from the advanced position — past the string end — returns false and resets to 0.
Explanation: Removing g makes the regex stateless — always starts from position 0. g is only needed when finding multiple matches with exec() in a loop.
Key Insight: The g flag makes regex stateful via lastIndex. Never use g for simple test() checks — it alternates true/false. Remove g or reset lastIndex = 0.