Read GET URL variables using JavaScript

Looking for a better way to manage your org's technical proposals?
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

Here is a function which will either build an associative array of the GET URL variables on the current page, or return the value of a specified GET variable in JavaScript:

function getUrlVar(requestedKey) {
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

  for (var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  if (typeof requestedKey == 'undefined') {
    return vars;
  } else {
    return vars[requestedKey];
  }
}

Usage:

var site_search = getUrlVar("site_search");
var all_vars = geturlVar();
var site_search_again = all_vars['site_search'];
Tags: #javascript
Thomas Hunter II Avatar

Thomas Hunter II is a Software Engineer with 18+ years building scalable, production-grade systems. Deep expertise in Node.js, observability, and developer tooling, with a strong track record of driving architectural decisions, mentoring engineers, and improving customer facing technical documentation. Author of 5 books (including O'Reilly), certified by the OpenJS Foundation, and frequent international conference speaker.