What is the meaning of the 'g' flag in regular expressions?

前端 未结 9 898

What is the meaning of the g flag in regular expressions?

What is is the difference between /.+/g and /.+/?

9条回答
  •  猫巷女王i
    2020-11-22 09:57

    As @matiska pointed out, the g flag sets the lastIndex property as well.

    A very important side effect of this is if you are reusing the same regex instance against a matching string, it will eventually fail because it only starts searching at the lastIndex.

    // regular regex
    const regex = /foo/;
    
    // same regex with global flag
    const regexG = /foo/g;
    
    const str = " foo foo foo ";
    
    const test = (r) => console.log(
        r,
        r.lastIndex,
        r.test(str),
        r.lastIndex
    );
    
    // Test the normal one 4 times (success)
    test(regex);
    test(regex);
    test(regex);
    test(regex);
    
    // Test the global one 4 times
    // (3 passes and a fail)
    test(regexG);
    test(regexG);
    test(regexG);
    test(regexG);

提交回复
热议问题