如何简洁地对URL列表进行过滤,使得每一个URL都必须通过一系列测试。如果URL匹配了任何一个测试,则应该被过滤掉。
我目前的方法是:
var _ = require("underscore");
const anchors = [
{href:"https://example.org/contact"},
{href:"https://example.org/faq"},
{href:"https://example.org/contact"},
{href:"https://example.org/uploads/image-1024x1018.jpg"},
{href:"https://example.org/wp-json/oembed/1.0/embed?url=example"},
{href:"https://example.org/author/pm"},
{href:"https://example.org/wp/wp-login.php?action=lostpassword"},
{href:"https://example.org/wp/wp-login.php"},
{href:"https://example.org/feed"},
];
const tests = [
/\/wp\//,
/\/wp-json\//,
/\.jpg$/,
/\.png$/,
/\.gif$/,
]
function testAll(testString){
let pass = true;
_.each(tests, t => {
if(t.test(testString)) pass = false;
});
return pass;
}
console.log(anchors.map(anchor => {
return anchor.href;
}).filter(anchor => {
return testAll(anchor);
}));
但我认为可以以更简洁的方式完成testAll
。
Array.prototype.every
- Mulantests.every(t => t.test(stringHere));
。every
只有在数组中的每个元素都返回true
时才会返回true
,因此你的函数就变成了:let anchorsPass = anchors.every(a => tests.every(t => t.test(a.href));
- tymeJV/$.png/
是在做什么?$
是字符串结尾的标志。 - Nina Scholz