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.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 has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, published a book on microservices, and is an organizer of Nodeschool SF.