Understanding Regex test on MDN

Asked

Viewed 49 times

0

Hello, searching on Regular Expression, I got a link to the MDN: [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test, But I looked, I looked and I didn’t understand why the example tested twice each variable, and why the last test returned false. The part of the example given, 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
  • 1

    The flag global serves for the pointer to advance each search. If you search for "X" in "AXBXCXDEFG" it will return true, true, true, false pq finds 3 times the value.

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 "g" flag is not used it is possible to repeat the test that the result is always the same. But when using the "g" flag a second test can give a different result from the first test, because the second test will skip the part of the string that has already been analyzed in the first test. Hence the repetition of tests on the site.

  • 1

    Great, I’m sorry I didn’t just read the MDN article a little bit more. Really... it’s there! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.