Home

Parsing GET Parameters in JavaScript

in JavaScript

Pretty simple way to parse query string parameters into an object for access in JavaScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
 * Params.js
 *
 * Super simple parser of query string parameters.
 * Creates a variable 'params' on the 'window' object.
 *
 */
(function() {
  var params     = {},
      capture    = void 0,
      query      = window.location.search.substring(1),
      whitespace = /\+/g,
      regex      = /([^&=]+)=?([^&]*)/g,
      decode     = function(s) {
        return decodeURIComponent(s.replace(whitespace, " "));
      };

  while (capture = regex.exec(query)) {
    var key   = decode(capture[1]),
        value = decode(capture[2]);

    if (value !== '') {
      params[key] = value;
    }
  }

  this.params = params;
}).call(this);