Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Last active December 7, 2020 11:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acdcjunior/9820040 to your computer and use it in GitHub Desktop.
Save acdcjunior/9820040 to your computer and use it in GitHub Desktop.
Cross-browser URL parsing in JavaScript
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;
}
// Use:
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
@acdcjunior
Copy link
Author

acdcjunior commented Jul 24, 2016

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"
}

@slavikme
Copy link

Sadly this doesn't support the extraction of password, username and searchParams.
Thanks though.

@acdcjunior
Copy link
Author

Actually, @slavikme, if I'm not mistaken, to get username and password, you only had to add it to the properties array on line 25. And, if by searchParams you mean a URLSearchParams, you could build one using this.search.

It is important to notice, though, that there may be today other better options for parsing a URL. This solution is good because it works for IE 6 and above, which is a lot. Perhaps your requirements are not as demanding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment