Using javascript to parse your URL into parts

Problem: Your site has a url that looks something like this:

You want to break it down into parts, for reasons that I’ll leave to your imagination.

Turns out that all the info you need is conveniently stored in the window.location object. Here’s the keys stored in the window.location object:


You can find out what each of them hold using this simple for loop:

//print out all window.location variables.
var loc = window.location;
for(var aKey in loc){

For example, if the url of the site is
you’ll find that

window.location.protocol = "http" = ""
window.location.pathname = "schedules/quickplanner

The variable holds the part of the string that’s after the pathname.
That is, in the BART url above, = ?orig=12TH&addr1=&dest=16TH&addr2=&type=departure&date=2013-12-21&time=9%3A00%20am&tab=2;

You can parse it into parts like so:

function get_search_from_url  (query) {
  if(!query || query.length==0) return query; // empty query string was input.
  var query_string = {};
  // get rid of the '?' at the beginning
  query = query.chartAt(0)=='?' ? query.substring(1,query.length) : query;
  // get the different parts
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    pair[0] = decodeURIComponent(pair[0]);
    pair[1] = decodeURIComponent(pair[1]);
    	// If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
    	// If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
    	// If third or later entry with this name
    } else {
  return query_string;

It basically does the opposite of jquery’s .param function.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s