字符串match()位置对正则exec()的影响

        var str = 'abc rbc fbc dbc';
        var reg = /.(bc)/g;
        var match1 = reg.exec(str);
        var match2 = str.match(reg);
        console.log(match1);
        console.log(reg.lastIndex);
        console.log(match1.index)
        match1 = reg.exec(str);
        console.log(match1);
        console.log(reg.lastIndex);
        console.log(match1.index)
        match1 = reg.exec(str);
        console.log(match1);
        console.log(reg.lastIndex);
        console.log(match1.index);
        //var match2 = str.match(reg);
        console.log(match2);

代码所示,我将var match2 = str.match(reg);的位置改变,输出的值是不一样的。

/5分钟之后更新/
哦哦,我傻了,match()相当于又执行了一次exec(),当然会改变lastIndex的值。。。。

阅读 1.8k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题