I’m confused:
function is_valid(name) {
var regexp_name = /^(\d|\w)*$/gi;
return regexp_name.test(name);
}
// Console
console.log(is_valid("Test"));
=> true
console.log(is_valid("Test"));
=> false
console.log(is_valid("Test"));
=> true
console.log(is_valid("Test"));
=> false
What am I doing wrong?
Remove the
/gflag.The RegExp object is somehow reused. When the
/gflag is present, the regex engine will start from the previous matched location until the whole string is consumed.BTW,
\wis equivalent to[0-9a-zA-Z_]in Javascript. Therefore, the\d|and the/iflag are redundant. And since you’re not using the captured group, there’s no need to keep the(…). This following is enough: