The same JavaScript function returns random results

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?

+3
source share
1 answer

Remove the flag /g.

The RegExp object is somehow reused. When a flag is present /g, the regex engine will start from the previous matching location until the entire line is destroyed.

 1st call:       Test
                 ^
 after 1st call: Test   (found "Test")
                     ^
 2nd call:       Test
                     ^
 after 2nd call  Test   (found nothing, reset)
                 ^

BTW, \wequivalent [0-9a-zA-Z_]in Javascript. Therefore, the flag \d|and /iare redundant. And since you are not using a captured group, there is no need to store (…). It's enough:

var regexp_name = /^\w*$/;
+6
source

Source: https://habr.com/ru/post/1756437/


All Articles