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

posted on 2023-08-25 14:47  糯米白白  阅读(4)  评论(0编辑  收藏  举报

导航