1

Consider the following:

 function filterFoods() {
   var foods = [
      {food: 'Bacon'}, {food: 'Butter'}, {food: 'Chicken'}, {food: 'Cocoa butter'},
      {food: 'Saussages'}, {food: 'Ham'}, {food: 'Duck'}, {food: 'Salmon'},
      {food: 'Fish'}, {food: 'Lamb'}, {food: 'Fries'}, {food: 'Tomatoes'},
      {food: 'Chicken'}, {food: 'Carrot'}, {food: 'Egg'}, {food: 'Avocado'},
      {food: 'Duck'}, {food: 'Hello'}, {food: 'Cheese'}, {food: 'Carrot'},
      {food: 'Potato'}, {food: 'Sweet Potato'}, {food: 'Pineapple'}, {food: 'Peanut'},
  ]
  return foods.filter(function(food) {
    return (/po/gi).test(food.food);
  });
}

console.log(
  filterFoods()
)

http://jsbin.com/gudekaruha/edit?js,console,output

I'm getting back [{food: 'Potato'},{food: 'Sweet Potato'}], which is what I want.

But I want to be able to pass something into the filterFoods function, and then into the regex, kind of like this:

 function filterFoods(query) {
   var foods = [
      {food: 'Bacon'}, {food: 'Butter'}, {food: 'Chicken'}, {food: 'Cocoa butter'},
      {food: 'Saussages'}, {food: 'Ham'}, {food: 'Duck'}, {food: 'Salmon'},
      {food: 'Fish'}, {food: 'Lamb'}, {food: 'Fries'}, {food: 'Tomatoes'},
      {food: 'Chicken'}, {food: 'Carrot'}, {food: 'Egg'}, {food: 'Avocado'},
      {food: 'Duck'}, {food: 'Hello'}, {food: 'Cheese'}, {food: 'Carrot'},
      {food: 'Potato'}, {food: 'Sweet Potato'}, {food: 'Pineapple'}, {food: 'Peanut'},
  ]
  return foods.filter(function(food) {
    return (/query/gi).test(food.food);
  });
}

console.log(
filterFoods('po')
)

But I'm getting back an empty array. Now correct me if I'm wrong but I think it's because I'm passing it in as a string, so how do I achieve this?

Thanks in advance

1
  • 1
    new RegExp(query, "gi"). Commented Oct 7, 2016 at 0:19

1 Answer 1

1

You need to use the RegExp() object.

return (new RegExp(query, 'gi')).test(food.food);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.