Match Anything with Wildcard Period. ()

Tell us what’s happening:
why does this test pass for some strings and not for others when I add flag g?
// running tests

Your regex unRegex should match “sun” in “The sun is out today.”

Your regex unRegex should match “pun” in “Seven days without a pun makes one weak.”

// tests completed

Your code so far


let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/gi; // Change this line
let result = unRegex.test(exampleStr);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period

Good question!

This has to do with the nature of the test() method for RegExp. When test() is called the first time on a regular expression with the global flag set, it remembers the index of the string where it stopped after the first match. So, for:

exampleStr = "Let us go on a run."

the lastIndex is 18. A subsequent use of test() will start the search at the substring of exampleStr specified by lastIndex.
So, when we change the string to

exampleStr = "The sun is out today.",

and start our search from index 18, we never have a chance to match ‘sun’.

According to MDN Web Docs,

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.

var regex = /foo/g;

// regex.lastIndex is at 0
regex.test('foo'); // true

// regex.lastIndex is now at 3
regex.test('foo'); // false

// regex.lastIndex is at 0
regex.test('barfoo') // true

// regex.lastIndex is at 6
regex.test('foobar') //false

Check out the Documentation:

3 Likes

Thank you so much willjw3 for the explanation and the link. Now I can say I know what to expect when I use the global flag.

1 Like