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 /g flag.
The RegExp object is somehow reused. When the /g flag is present, the regex engine will start from the previous matched location until the whole string is consumed.
1st call: Test
^
after 1st call: Test (found "Test")
^
2nd call: Test
^
after 2nd call Test (found nothing, reset)
^
BTW, \w is equivalent to [0-9a-zA-Z_] in Javascript. Therefore, the \d| and the /i flag are redundant. And since you're not using the captured group, there's no need to keep the (…). This following is enough:
var regexp_name = /^\w*$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With