Reading Query String with JavaScript

When you google on this topic you will find many ways to get Query String parameters & its values using JavaScript. Below is one of the smallest, easiest and a clean code for the same purpose. I found this code from Ben Nadel’s Blog post mentioned below.

   1: function GetQueryStringValue(parameterName) {

   2:  var objQRs = new Object();

   3:  

   4:  window.location.search.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"),

   5:              function($0, $1, $2, $3) { objQRs[$1] = $3; });

   6:              

   7:  return objQRs[parameterName]

   8: }  

So if you have a url like  page.html?id=1000&code=zoox&dt=10/31/2009 you can use following code to retrieve the  values of querystring parameters id, code and dt.

   1: var id= GetQueryStringValue("id");

   2: var code = GetQueryStringValue("code");

   3: var dateValue = GetQueryStringValue("dt");

If the parameter key passed to GetQueryStringValue() does not exists in query string then it returns ‘undefined’.

References:

Ask Ben: Getting Query String Values In JavaScript

   2:  var objQRs = new Object();

   3:  

   4:  window.location.search.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"),

   5:              function($0, $1, $2, $3) { objQRs[$1] = $3; });

   6:              

   7:  return objQRs[parameterName]

   8: }  

So if you have a url like  page.html?id=1000&code=zoox&dt=10/31/2009 you can use following code to retrieve the  values of querystring parameters id, code and dt.

   1: var id= GetQueryStringValue("id");

   2: var code = GetQueryStringValue("code");

   3: var dateValue = GetQueryStringValue("dt");

If the parameter key passed to GetQueryStringValue() does not exists in query string then it returns ‘undefined’.

References:

Ask Ben: Getting Query String Values In JavaScript

-->