开发者

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("Tes开发者_如何学Got"));
=> 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*$/;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜