URL解析

使用JavaScript对URL进行解析,提取其中的键值对

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Resolve URL</title>
</head>
<body>
<script>
    var url="http://guangzai:hello@www.abc.com:8080/lujing/list.pathname?id=123&name=guang#top";

    function parseUrl(url){
        //创建 <a>标签元素,使其 href 属性指向 url,这样就可以使用 HTMLHyperlinkElementUtils 提供的属性了
        var link=document.createElement("a");
        link.href=url;            
        return {
            //href 包括整个URL
            url:link.href,

            //获取 protocol 默认包括冒号
            protocol:link.protocol.replace(":",""),//如 http:
            
            username:link.username,//如 guangzai
            password:link.password,//如 hello

            //获取 host 默认包括端口,但不包括默认端口
            host:link.host,//如 www.example.com:5678

            //获取 hostname 不包括端口
            hostname:link.hostname,//如 www.example.com

            //获取 port 默认端口则返回字符串
            port:link.port,    //如 1234

            //获取 origin 包括 protocol+host
            origin:link.origin,

            //获取 pathname 包括 origin -- search 之间的字符
            pathname:link.pathname,//如 /source/index.pathname , /source/images , /source/images/

            //search 返回 URL中的所有参数及相关符号,如 ?id=123&name=guang
            parameters:(()=>{
                var param={};//定义对象用于存储参数
                var searchArr=link.search.replace("?","").split("&");//去除问号并分割参数字符串,存储在数组中
                searchArr.forEach((item)=>{
                    var arr=item.split("=");//分割参数字符串,存储在数组中
                    param[arr[0]]=arr[1];//将参数名以及对应的值存在在对象中
                })
                return param;//返回最终的结果
            })(),

            //获取 hash 默认包括井号
            hash:link.hash.replace("#",""),
        }            
    }

    console.log(parseUrl(url));

    //上述例子返回的结果如下:
    var result=
          {
          "url": "http://guangzai:hello@www.abc.com:8080/lujing/list.pathname?id=123&name=guang#top",
          "protocol": "http",
          "username": "guangzai",
          "password": "hello",
          "host": "www.abc.com:8080",
          "hostname": "www.abc.com",
          "port": "8080",
          "origin": "http://www.abc.com:8080",
          "pathname": "/lujing/list.pathname",
          "parameters": {
            "id": "123",
            "name": "guang"
          },
          "hash": "top"
        }

</script>
</body>
</html>
原文地址:https://www.cnblogs.com/go4it/p/10143592.html