Parsing Querystring in a URL Through JavaScript

To parse a query string in a URL through JS, you can use a function like the following one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getQueryValue(param) {
  var qstring = window.location.search,
      qstringArray = qstring && qstring.substring(1).split("&"),
      i = 0,
      len = qstringArray.length;
  for (; i < len; i++) {
      var token = qstringArray[i],
          eqIndex = token.indexOf("="),
          firstPart = token && token.substring(0, eqIndex);
      if (firstPart === param ) {
          return token.substring(eqIndex + 1, token.length);
      }
  }
}

E.g. Given a URL “http://domain.com.au?aaa=bbb” , you can call this function as getQueryValue(“aaa”) and youll get “bbb”

I uploaded this code in a Gist on Github (bit modified to be compliant with the module pattern).

Comments