Kreitzo Kreitzo - 2 months ago 7
Javascript Question

Pass a string into regex

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

Answer

You need to use the RegExp() object.

return (new RegExp(query, 'gi')).test(food.food);