Why this regex it's not working properly? [solved]

ghaerdi

Gil Rudolf Härdi

Posted on August 29, 2021

Why this regex it's not working properly? [solved]

I have a function that filter a food list and returns a fruit list.
The expected result is: ["apple", "banana", "watermelon"] but the next code don't push watermelon in the array.

const foodList = ["apple", "soap", "banana", "watermelon", "pizza"];

function getFruits(foodList) {
  const fruitRGX = /apple|banana|watermelon/g;
  const fruitList = [];

  for (const food of foodList) {
    if (!fruitRGX.test(food)) continue;

    fruitList.push(food);
  }

  return fruitList;
}

const fruits = getFruits(foodList);
const expect = ["apple", "banana", "watermelon"];

console.log({ fruits, expect });
// output:
// {
//  fruits: [ "apple", "banana" ],
//  expect: [ "apple", "banana", "watermelon" ]
// }
Enter fullscreen mode Exit fullscreen mode

If I remove the g flag in the fruitRGX or I move the constant declaration inside the for loop then fruits is equal to expect.

Can someone explain what happening?

Edit

I already get the answer since the first comment, see my reply or Ben Calder's comment if you want see a quick explain about this problem.

💖 💪 🙅 🚩
ghaerdi
Gil Rudolf Härdi

Posted on August 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related