我有一个像这样的字符串数组: ['http://www.google.com','https://www.facebook.com','stackoverflow']
我要对其进行过滤以仅接受有效的URL?
我以这种方式解决它:
var patternAbsoluteLinks = /^https?:\/\//i;
var url = [];
links.map(link => {
if (patternAbsoluteLinks.test(link.getAttribute("href"))) {
urls.push(link.getAttribute("href"));
}
});
如何以更优雅的方式解决此问题? 我尝试使用过滤器,但不起作用:
const matchedSitesSuccess = links.filter(href =>
patternAbsoluteLinks.test(link.getAttribute("href"))
);
谢谢!
答案 0 :(得分:0)
类似这样的东西:
const arr = ['http://www.google.com','https://www.facebook.com','stackoverflow'];
const isValidUrl = url => {
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
return regexp.test(url);
}
const validUrls = arr.filter(isValidUrl);
console.log(validUrls);