我有一个 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)
);
但似乎没有用。由于某种原因,它返回 false。我尝试了不同的变体,但找不到一个有效的变体。
最佳答案
您需要使用 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)
关于javascript - 使用 reduce 检查数组是否包含与字符串匹配的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751512/