使用 reduce 检查数组是否包含与字符串匹配的正则表达式

check whether an array contains a regex that matches with a string, using reduce

我在 JavaScript 中有一个正则表达式列表,如下所示:

var list = [
 '^/items/detail.*',
 '^/items/settings.*',
 '^/article/view/.*',
 '^/home/purchase.*',
];

我想查看字符串是否与数组中的正则表达式之一匹配。 如果可能的话,我想使用reduce。

我试过这个:

var text = "http://www.mypage.com/items/detail";
var result = list.reduce((a, b) =>
  !!text.match(a) || !!text.match(b)
);

但似乎不起作用。由于某种原因,它 returns 错误。我尝试了不同的变体,但找不到有效的变体。

您需要使用 RegExp() 并添加一个附加条件 a === true 因为 a 将在第二次迭代时为真或假

var list = [
  '/items/detail.*',
  '^/items/settings.*',
  '^/article/view/.*',
  '^/home/purchase.*',
];

var text = "http://www.mypage.com/items/detail";
var result = list.reduce((a, b) =>
  a === true || (a !== false && !!text.match(RegExp(a))) || !!text.match(RegExp(b))
);

console.log(result)


更新:

根据 @zerkms 建议的更简化版本,通过提供额外的 initialValue 作为 false

var list = [
  '/items/detail.*',
  '^/items/settings.*',
  '^/article/view/.*',
  '^/home/purchase.*',
];

var text = "http://www.mypage.com/items/detail";
var result = list.reduce((a, b) => a || RegExp(b).test(text), false)

console.log(result)