Skip to content

Instantly share code, notes, and snippets.

@jakedetels
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakedetels/6ab647ad20a53cbbdd99 to your computer and use it in GitHub Desktop.
Save jakedetels/6ab647ad20a53cbbdd99 to your computer and use it in GitHub Desktop.
JavaScript Utility for Getting/Setting URL Query Parameters

The location.params() function (shown below) can be used as a getter or setter. Examples:

Given the URL is http://example.com/?foo=bar&baz#some-hash,

  1. location.params() will return an object with all the query parameters: {foo: 'bar', baz: true}.
  2. location.params('foo') will return 'bar'.
  3. location.params({foo: undefined, hello: 'world', test: true}) will change the URL to http://example.com/?baz&hello=world&test#some-hash.

Here is the params() function, which can optionally be assigned to the window.location object.

location.params = function(params) {
  var obj = {}, i, parts, len, key, value;

  if (typeof params === 'string') {
    if (arguments.length === 2) {
      obj[params] = arguments[1];
      params = obj;
      obj = {};
    } else {
      value = (location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?')) || [])[1];
      return value === '' ? true : value;
    }
  }

  var _params = location.search.substr(1).split('&');

  for (i = 0, len = _params.length; i < len; i++) {
    parts = _params[i].split('=');
    if (! parts[0]) {continue;}
    obj[parts[0]] = parts[1] || true;
  }

  if (typeof params !== 'object') {return obj;}

  for (key in params) {
    value = params[key];
    if (typeof value === 'undefined') {
      delete obj[key];
    } else {
      obj[key] = value;
    }
  }

  parts = [];
  for (key in obj) {
    parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
  }

  location.search = parts.join('&');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment