How do I parse a URL into hostname and path in javascript?

前端 未结 22 1767
南方客
南方客 2020-11-21 22:38

I would like to take a string

var a = \"http://example.com/aa/bb/\"

and process it into an object such that

a.hostname == \         


        
22条回答
  •  天命终不由人
    2020-11-21 23:15

    Expanded on acdcjunior solution by adding "searchParam" function
    Mimicking the URL object, added "searchParam" to parse query string
    Works for IE 6, 7, 8 9, 10, 11

    USAGE - (JSFiddle Link)

    // USAGE:
    var myUrl = new ParsedUrl("http://www.example.com/path?var1=123&var2=abc#fragment");
    console.log(myUrl);
    console.log(myUrl.searchParam('var1'));
    console.log(myUrl.searchParam('var2'));
    

    OUTPUT - (JSFiddle Link)

    {
      hash: "#fragment",
      host: "www.example.com:8080",
      hostname: "www.example.com",
      href: "http://www.example.com:8080/path?var1=123&var2=abc#fragment",
      pathname: "/path",
      port: "80",
      protocol: "http:",
      search: "?var1=123&var2=abc"
    }
    
    "123"
    "abc"
    

    CODE - (JSFiddle Link)

    function ParsedUrl(url) {
        var parser = document.createElement("a");
        parser.href = url;
        
        // IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
        // is just a pathname, that is, "/example" and not "http://www.example.com/example".
        parser.href = parser.href;
        
        // IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
        // so we take the protocol/host from window.location and place them manually
        if (parser.host === "") {
            var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
            if (url.charAt(1) === "/") {
                parser.href = newProtocolAndHost + url;
            } else {
                // the regex gets everything up to the last "/"
                // /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
                // "/" is inserted before because IE takes it of from pathname
                var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
                parser.href = newProtocolAndHost + currentFolder + url;
            }
        }
        
        // copies all the properties to this object
        var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
        for (var i = 0, n = properties.length; i < n; i++) {
          this[properties[i]] = parser[properties[i]];
        }
        
        // pathname is special because IE takes the "/" of the starting of pathname
        this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
      
      //search Params
      this.searchParam =  function(variable) {
        var query = (this.search.indexOf('?') === 0) ? this.search.substr(1) : this.search;
        var vars = query.split('&');
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=');
            if (decodeURIComponent(pair[0]) == variable) {
                return decodeURIComponent(pair[1]);
            }
        }
        console.log('Query variable %s not found', variable);
        return '';
        };
    }
    

提交回复
热议问题