JS 验证URL是否有效
function isValidHttpUrl(string) {
try {
const newUrl = new URL(string);
return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';
} catch (err) {
return false;
}
}
console.log(isValidHttpUrl('https://www.baidu.com')); // true
console.log(isValidHttpUrl('mailto://mail@baidu.com')); // false
console.log(isValidHttpUrl('baidu')); // false