Skip to content

Instantly share code, notes, and snippets.

@jdunck
Created September 16, 2010 20:56
Show Gist options
  • Save jdunck/583153 to your computer and use it in GitHub Desktop.
Save jdunck/583153 to your computer and use it in GitHub Desktop.
A window.location-compatible URL parsing class
// Location shim 1.0
// (c) Jeremy Dunck
// MIT License
function Location(url) {
obj = parseUri(url);
this.hash = obj.anchor ? "#" + obj.anchor : "";
this.host = obj.authority;
this.hostname = obj.host;
this.href = url;
this.pathname = obj.path;
this.port = obj.port;
this.protocol = obj.protocol;
this.search = obj.query ? "?" + obj.query : "";
this.queryKey = obj.queryKey;
this.toString = function() {
return this.href;
}
}
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment