Wildcard Match Anything with Period Test Issue

Tell us what’s happening:

Your code so far


let exampleStr = "The sun is out today.";
let unRegex = /.un/g; // Change this line
let result = unRegex.test(exampleStr);
console.log(exampleStr.match(unRegex));
console.log(result); 
exampleStr = "Seven days without a pun makes one weak.";
console.log(exampleStr.match(unRegex));
console.log(result); 

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0.

The above string examples will not pass the challenge test, yet they do log properly to the console. Befuddled.

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

Do you have a question?

Re-read the lesson. Sometimes it’s the small things. Did they tell you to use the global flag?

Yes. The code that I had written for this challenge, when tested with :

let exampleStr = "The sun is out today.";
exampleStr = "Seven days without a pun makes one weak.";
console.log(exampleStr.match(unRegex));
console.log(result);

The log reads in the console:

sun //as a string
true //as a boolean

pun //as a string
true //as a boolean

yet the challenge tests for those sentences does not clear.
I’m curious as to why.

As @Roma pointed out, you want to be careful when applying the global flag. Look at how the .test() method works with a global regex:

I did use global and the wildcard identifier.

Why would the global designation cause issues in these cases? There was also only one match in each string so the boolean could not be flipped.

Don’t do that

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.

1 Like

Thanks for the lesson. Is there documentation that I can view with regard to this characteristic.

In my previous post there is linked the documentation on the test method, it is the source of my quote