Last active
December 14, 2015 09:49
-
-
Save mattfelten/5067297 to your computer and use it in GitHub Desktop.
Helps with messing with URLs and grabbing their query vars.
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
$.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