Daily Coding Challenge - Image Search

Tell us what’s happening:

regexp.exec() with g flag doesn’t recognize “catNip.jpeg” - why?
I know it works fine without g and also works with String’s .match(), but I don’t understand the reason.

Your code so far

function imageSearch(images, term) {
  const regexp = new RegExp(term, "ig");
  const foundImages = images.filter(imgName => regexp.exec(imgName));

  return foundImages;
}

console.log(
  imageSearch(["cat.jpg", "dogToy.jpeg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"], "Cat")
);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:159.0) Gecko/20100101 Firefox/159.0

Challenge Information:

Daily Coding Challenge - Image Search

https://www.freecodecamp.org/learn/daily-coding-challenge/11-04

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a5.md at main · freeCodeCamp/freeCodeCamp · GitHub

When you use the g flag, the regex starts from the lastIndex which is the index at which it last found a match, so kitty-cat.png makes the lastIndex to 7, then in catNip.jpeg it starts checking from index 7, not 0, and finds nothing

this happens also with test, eventually you meet this and learn. use g only when you know you need it.

Ohhhh I think I get it. So, it basically doesn’t care that all the strings are different and keeps searching as if it was just one string passed all the time?

the lastIndex property is of the regex, not of the string, so it does not matter if the string changes