Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same JavaScript function returns random results

Tags:

javascript

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?

like image 536
Poru Avatar asked Dec 18 '25 08:12

Poru


1 Answers

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*$/;
like image 146
kennytm Avatar answered Dec 20 '25 21:12

kennytm