Created
September 25, 2013 23:55
-
-
Save lfender6445/6707904 to your computer and use it in GitHub Desktop.
jQuery convert query string to json
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
query_to_hash = function() { | |
var j, q; | |
q = window.location.search.replace(/\?/, "").split("&"); | |
j = {}; | |
$.each(q, function(i, arr) { | |
arr = arr.split('='); | |
return j[arr[0]] = arr[1]; | |
}); | |
return j; | |
} | |
With Array.prototype.reduce
var query_to_hash = function(queryString) {
var query = queryString || location.search.replace(/\?/, "");
return query.split("&").reduce(function(obj, item, i) {
if(item) {
item = item.split('=');
obj[item[0]] = item[1];
return obj;
}
}, {});
};
query_to_hash();
<= current url query string
query_to_hash('page=1');
<= parse query string
improved above with es6 and decode uri param, also always return in array.reduce, also replacing only starting ? and in any param
function getQueryParams (query = window.location.search) {
return query.replace(/^\?/, '').split('&').reduce((json, item) => {
if (item) {
item = item.split('=').map((value) => decodeURIComponent(value))
json[item[0]] = item[1]
}
return json
}, {})
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For something you can put in a toolbox-snippet: