# 题目描述

请你以Boolean的形式返回字符串参数是否为合法的URL格式。

注意

协议仅为HTTP(S)

# 分析

参考代码注释

# 代码实现

const _isUrl = url => {
    // 补全代码

    // 开始符
    // 协议名: http(s):// 表示 ((https|http)?:\/\/) 
    // 没有可以,但是有的话只能有其中的一个
    // 域名部分 主机名可以使用"-"符号,所以两种情况都要判断,包含"-"或不包含"-"
    // 顶级域名:com, cn 长度为2-6   表示为 [a-zA-Z]{2,6}
    // 端口部分     表示为(:\d+)?, ?表示0次或1次
    // 请求路径如/login        表示为 (\/.*)?
    // 问号传参及哈希值如?age=1  表示为 (\?.*)?和(#.*)?
    // 结束符 $
    
   let req = /^((https|http|ftp|rtsp|mms)?:\/\/)(([a-zA-Z0-9]+|[a-zA-Z0-9]+-[a-zA-Z0-9]+)\.)+([a-zA-Z]{2,6})(:\d+)?(\/.*)?(\?.*)?(#.*)?$/;

   return req.test(url);
}
function test() {
  const judge1 = _isUrl("http://.com:80?name=?&age=1");
  const judge2 = _isUrl("https://a.b.c.com:8080/get?name=?&age=1");
  const result = !judge1 && judge2;
  return result;
}

console.log(test());
// true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26