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

前端 未结 22 1128
南方客
南方客 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条回答
  • today I meet this problem and I found: URL - MDN Web APIs

    var url = new URL("http://test.example.com/dir/subdir/file.html#hash");
    

    This return:

    { hash:"#hash", host:"test.example.com", hostname:"test.example.com", href:"http://test.example.com/dir/subdir/file.html#hash", origin:"http://test.example.com", password:"", pathname:"/dir/subdir/file.html", port:"", protocol:"http:", search: "", username: "" }
    

    Hoping my first contribution helps you !

    0 讨论(0)
  • 2020-11-21 23:21

    What about simple regular expression?

    url = "http://www.example.com/path/to/somwhere";
    urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
    hostname = urlParts[1]; // www.example.com
    path = urlParts[2]; // /path/to/somwhere
    
    0 讨论(0)
  • 2020-11-21 23:21

    Cross-browser URL parsing, works around the relative path problem for IE 6, 7, 8 and 9:

    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://domain.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;
    }
    

    Usage (demo JSFiddle here):

    var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
    

    Result:

    {
        hash: "#fragment"
        host: "www.example.com:8080"
        hostname: "www.example.com"
        href: "http://www.example.com:8080/path?query=123#fragment"
        pathname: "/path"
        port: "8080"
        protocol: "http:"
        search: "?query=123"
    }
    
    0 讨论(0)
  • 2020-11-21 23:21

    a simple hack with the first answer

    var getLocation = function(href=window.location.href) {
        var l = document.createElement("a");
        l.href = href;
        return l;
    };
    

    this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname

    0 讨论(0)
  • 2020-11-21 23:22

    js-uri (available on Google Code) takes a string URL and resolves a URI object from it:

    var some_uri = new URI("http://www.example.com/foo/bar");
    
    alert(some_uri.authority); // www.example.com
    alert(some_uri);           // http://www.example.com/foo/bar
    
    var blah      = new URI("blah");
    var blah_full = blah.resolve(some_uri);
    alert(blah_full);         // http://www.example.com/foo/blah
    
    0 讨论(0)
  • 2020-11-21 23:23
    var loc = window.location;  // => "http://example.com:3000/pathname/?search=test#hash"
    

    returns the currentUrl.

    If you want to pass your own string as a url (doesn't work in IE11):

    var loc = new URL("http://example.com:3000/pathname/?search=test#hash")
    

    Then you can parse it like:

    loc.protocol; // => "http:"
    loc.host;     // => "example.com:3000"
    loc.hostname; // => "example.com"
    loc.port;     // => "3000"
    loc.pathname; // => "/pathname/"
    loc.hash;     // => "#hash"
    loc.search;   // => "?search=test"
    
    0 讨论(0)
提交回复
热议问题