Getting Query Parameters in Javascript

I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function.

What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously.

// Creates associative array (object) of query params var QueryParameters = (function() {     var result = {};

    if (window.location.search)     {         // split up the query string and store in an associative array         var params = window.location.search.slice(1).split("&");        for (var i = 0; i < params.length; i++)         {             var tmp = params[i].split("=");             result[tmp[0]] = unescape(tmp[1]);         }     }

    return result; }());

Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it.

var debug = (QueryParameters.debug === "true");

or

if (QueryParameters["debug"]) doSomeDebugging();

or loop through all of the parameters.

for (var param in QueryParameters) var value = QueryParameters[param];

Hope you find this object useful.

This article is part of the GWB Archives. Original Author: PhubarBaz

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.