Design & Download
Your JS Library
in Seconds!!!

Snippet: Parsing URL Query Strings

Written by Christopher West (cwest) on November 30, 2015.
Parses a URL to get the parameters specified in the query string.
function parseQS(url) {
  var vars = {};
  url.replace(/\?[^#]+/, function(query) {
    query.replace(/\+/g, ' ').replace(/[\?&]([^=&#]+)(?:=([^&#]*))?/g, function(m, key, value, arrIndicator, alreadyDefined, lastValue) {
      key = decodeURIComponent(key);
      if (arrIndicator = key.slice(-2) == '[]') {
        key = key.slice(0, -2);
      value = value && decodeURIComponent(value);
      alreadyDefined = has(vars, key);
      lastValue = vars[key];
      vars[key] = arrIndicator || alreadyDefined
        ? typeOf(lastValue, 'Array')
          ? lastValue.concat([value])
          : alreadyDefined
            ? [lastValue, value]
            : [value]
        : value;
  return vars;

In jPaq I had defined an object called jPaq.GET which contained the variables passed via the query string of the page's URL. This time around, I decided to avoid that technique and instead allow the developer to choose which URLs to parse in order to get an object of the variables found in the query string.

parseQS API Documentation


Parses a URL to get the parameters specified in the query string.


  1. url {String}:
    The URL to parse.


Returns an object in which the keys are the keys of the parameters found in url and the values are the corresponding values found in url. If a parameter key is specified twice or ends in "[]", that property will be an array of all of the found values for that key.