Read GET URL variables using JavaScript

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[hash[0]] = hash[1];
  if (typeof requestedKey == 'undefined') {
    return vars;
  } else {
    return vars[requestedKey];


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 is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.