search

Home  >  Q&A  >  body text

RegExp instance usage issue exec() method - Stack Overflow

var text = "cat, bat, sat, fat";
var pattern2 = /.at/g;
var matches = pattern2.exec(text);
console.log(matches.index);   //0
console.log(matches[0]);   //cat
console.log(pattern2.lastIndex);   //3
matches = pattern2.exec(text);
console.log(matches.index);   //5,为什么是5,不应该从fat开始吗?
console.log(matches[0]);   //bat
console.log(pattern2.lastIndex);   //8

Why should we start from bat instead of fat?

phpcn_u1582phpcn_u15822736 days ago831

reply all(2)I'll reply

  • 阿神

    阿神2017-05-18 11:03:08

    No, it goes backwards one by one. In the first round, it matches at in cat, and the index is changed to start with the comma after cat, which is 3. Then it continues to go back and matches at in bat, and the index is 5. .just like the 0 at the beginning.

    reply
    0
  • 为情所困

    为情所困2017-05-18 11:03:08

    //5, why is it 5? Shouldn’t we start with fat?
    Are you wondering whether you should start with cat. .
    If this is the case, just remove the g at the end of the regular expression

    reply
    0
  • Cancelreply