gpt4 book ai didi

javascript - 检查 JavaScript 字符串是否为 URL

转载 作者:IT老高 更新时间:2023-10-28 13:14:25 28 4
gpt4 key购买 nike

JavaScript 中有没有办法检查字符串是否为 URL?

RegExes 被排除在外,因为 URL 很可能写成 stackoverflow;也就是说,它可能没有 .comwwwhttp

最佳答案

如果要检查字符串是否是有效的HTTP URL,可以使用URL constructor (它会抛出格式错误的字符串):

function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
console.log("http://example.com: "+isValidHttpUrl("https://example.com"));
console.log("example.com: "+isValidHttpUrl("example.com"));

注意:根据 RFC 3886 , URL 必须以方案开头(不限于 http/https),例如。 g.:

  • www.example.com 是无效的 URL(缺少方案)
  • javascript:void(0) 是有效的 URL,虽然不是 HTTP 的
  • http://.. 是主机为 .. 的有效 URL(是否解析取决于您的 DNS)
  • https://example..com 是有效的 URL,同上

关于javascript - 检查 JavaScript 字符串是否为 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5717093/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com