Skip to content

Instantly share code, notes, and snippets.

@lfender6445
Created September 25, 2013 23:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lfender6445/6707904 to your computer and use it in GitHub Desktop.
Save lfender6445/6707904 to your computer and use it in GitHub Desktop.
jQuery convert query string to json
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;
}
@nicolasembleton
Copy link

For something you can put in a toolbox-snippet:

query_to_hash = function(queryString) {
  var j, q;
  q = queryString.replace(/\?/, "").split("&");
  j = {};
  $.each(q, function(i, arr) {
    arr = arr.split('=');
    return j[arr[0]] = arr[1];
  });
  return j;
}

var queryStringToHash = "";
var queryHash = JSON.stringify(query_to_hash(queryStringToHash);
console.log(queryHash);

@gracefullight
Copy link

gracefullight commented Sep 15, 2017

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

@Prozi
Copy link

Prozi commented Apr 9, 2018

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