-
-
Save rc1021/58ae77007343013907f2f98e641ba126 to your computer and use it in GitHub Desktop.
Cross-browser URL parsing in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ParsedUrl(url) { | |
this.parse(url); | |
} | |
ParsedUrl.prototype.parse = function (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; | |
} | |
ParsedUrl.prototype.set = function (attr_name, attr_value) { | |
this[attr_name] = attr_value; | |
this.parse(this.toString()); | |
} | |
ParsedUrl.prototype.toString = function () { | |
return (this.protocol || "http:") + "//" + this.hostname + | |
((this.port) ? ":" + this.port : "") + | |
((this.pathname) ? this.pathname : "/") + | |
((this.search) ? this.search : "") + | |
((this.hash) ? this.hash : ""); | |
} | |
// Use: | |
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
prototype.set
andprototype.toString
Result: