Skip to content

Instantly share code, notes, and snippets.

@mattfelten
Last active December 14, 2015 09:49
Show Gist options
  • Save mattfelten/5067297 to your computer and use it in GitHub Desktop.
Save mattfelten/5067297 to your computer and use it in GitHub Desktop.
Helps with messing with URLs and grabbing their query vars.
$.getLocationObj = function(url) {
var query, match,
a = document.createElement('a'),
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
urlParams = {},
b = {};
a.href = url;
query = a.search.substring(1);
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
a.var = urlParams;
return a;
}
// Usage
var url = $.getLocationObj('http://mattfelten.com/test/?var1=test&var2=test2');
// url.origin = http://mattfelten.com
// url.pathname = /test/
// url.var.var1 = test
// url.var.var2 = test2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment