Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.search query as JSON

Tags:

Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });
like image 867
thugsb Avatar asked Jun 30 '11 19:06

thugsb


1 Answers

Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)

function searchToObject() {
  var pairs = window.location.search.substring(1).split("&"),
    obj = {},
    pair,
    i;

  for ( i in pairs ) {
    if ( pairs[i] === "" ) continue;

    pair = pairs[i].split("=");
    obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
  }

  return obj;
}

On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)

like image 63
Carlo Zottmann Avatar answered Oct 14 '22 20:10

Carlo Zottmann