DEV Community

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

Collapse
 
mireslami809 profile image
mireslami-hossein

you can do like this:

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

let fruitList = []
function getFruits(foodList) {
  const fruitRGX = /apple|banana|watermelon/g;
  foodList.forEach(food =>{
      if(food.match(fruitRGX)){
        fruitList.push(food)
      }
  })

  return fruitList
}

console.log(getFruits(foodList))
// output: ["apple", "banana", "watermelon"]

Enter fullscreen mode Exit fullscreen mode

I think if you use match(regex) instead of test() is better.
and you can use array.forEach() instead of for() for better readability!

Collapse
 
ghaerdi profile image
Gil Rudolf Härdi

Thanks for the advise, what I really need is to know what happened with my code.

What is the reason for not output watermelon?

But somehow your code is very helpful, you used match and it worked well so my question has changed to why test don't worked but match yes?. This time I found the info that I want:
The RegEx object has a property called lastIndex updated with test method, that property don't reset when test returns true. If the same regex is used again then can happen what happened with my code.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

@ghaerdi I have explained this weird behavior of test method in my this article.

Collapse
 
frondor profile image
Federico Vázquez

Or better yet, a pure function:

const knownFruits = new Set(["apple", "banana", "watermelon"])

function getFruits(foodList) {
  return foodList.filter(food => knownFruits.has(food))
}
Enter fullscreen mode Exit fullscreen mode