Understanding RegEx test in MDN

0

Hello, searching for Regular Expression, I've got a link to MDN: [1]: link , but I looked, looked and did not understand because the example tested twice each variable, and because the last test returned false. The part of the given example, which I need to understand is:

var regex1 = RegExp('foo*');

var regex2 = RegExp('foo*','g');

var str1 = 'table football';

console.log(regex1.test(str1));

// expected output: true

console.log(regex1.test(str1));      // porque testar de novo?

// expected output: true

console.log(regex2.test(str1));

// expected output: true

console.log(regex2.test(str1));      // por que testar de novo e por que retornou false?

// expected output: false
    
asked by anonymous 28.10.2018 / 02:38

1 answer

2

The explanation is there:

  

Using test () on a regex with the global flag

     

If the regex has the global flag set, test () will advance the lastIndex of the regex. A subsequent use of test () will start the search at the substring of str specified by lastIndex (exec () will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

What does this mean? That when the flag "g" is not used it is possible to repeat the test that the result is always the same. But when using flag "g" a second test may give a different result from the first test, because the second test will skip the part of the string that was already analyzed in the first test. This is why repeat testing on the site.

    
28.10.2018 / 02:55