将字符串传递给正则表达式

时间:2016-10-07 00:18:12

标签: javascript regex

请考虑以下事项:

 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

我回来了[{food: 'Potato'},{food: 'Sweet Potato'}],这就是我想要的。

但是我希望能够将一些东西传递给filterFoods函数,然后传递到正则表达式,就像这样:

 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')
)

但是我回来了一个空数组。现在纠正我,如果我错了,但我认为这是因为我把它作为一个字符串传递给我,所以我该如何实现呢?

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用RegExp()对象。

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