Monday, January 28, 2013

TIP: Get Query String Values Using JavaScript

Use the following simple script to pull values from the query string:

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1);
  var keyValues = queryString.split('&');
  for(var i in keyValues) {
    var key = keyValues[i].split('=');
    if (key.length > 1) {
      assoc[decode(key[0])] = decode(key[1]);
    }
  }
  return assoc;
}
var qs = getQueryStrings();
var myParam = qs["myParam"]; 
Notes
  • There are number of variations on this script, but this was the simplest that I could find - but I can't recall from whom I obtained this script!  I just wrote it down and forgot about it.  If you know, please enter a comment so that I can properly attribute this great script.  UPDATE: found it: proper credit goes to: How to get the query string by javascript?
  • I use this script for pulling values from query strings used to build dashboards.

No comments: