美文网首页
最简单的URL解析方法

最简单的URL解析方法

作者: 大前端之路 | 来源:发表于2017-01-24 17:00 被阅读0次
    function parseURL(url) {
      var parser = document.createElement("a"),
          searchObj = {},
          queries,key, value
    
      parser.href = url
      queries = parser.search.replace(/^\?/, "").split("&")
      queries.forEach((query) => {
        key = query.split("=")[0]
        value = query.split("=")[1]
        searchObj[key] = value
      })
    
      return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        searchObj: searchObj,
        hash: parser.hash
      }
    }
    
    new URL('https://gist.github.com/jlong/2428561?foo=bar#test') =>
        {
            hash: "#test",
            search: "?foo=bar",
            pathname: "/jlong/2428561",
            port: "",
            hostname: "gist.github.com",
            host: "gist.github.com",
            password: "",
            username: "",
            protocol: "https:",
            origin: "https://gist.github.com",
            href: "https://gist.github.com/jlong/2428561?foo=bar#test"
        }
    
        var parser = document.createElement('a');
        parser.href = "http://example.com:3000/pathname/?search=1&a=2#hash";
    
        parser.protocol; // => "http:"
        parser.hostname; // => "example.com"
        parser.port;     // => "3000"
        parser.pathname; // => "/pathname/"
        parser.search;   // => "?search=test"
        parser.hash;     // => "#hash"
        parser.host;     // => "example.com:3000"
    
        console.log(parser.search);
    

    相关文章

      网友评论

          本文标题:最简单的URL解析方法

          本文链接:https://www.haomeiwen.com/subject/vbgzbttx.html