Using javascript to parse your URL into parts

Problem: Your site has a url that looks something like this: http://www.bart.gov/schedules/quickplanner?orig=12TH&addr1=&dest=16TH&addr2=&type=departure&date=2013-12-21&time=9%3A00%20am&tab=2

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:

ancestorOrigins
constructor
hash
host
hostname
href
origin
pathname
port
protocol
search

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){
 console.log(aKey+":",loca[aKey]);
}

For example, if the url of the site is http://www.bart.gov/schedules/quickplanner
you’ll find that

window.location.protocol = "http"
window.location.host = "www.bart.gov"
window.location.pathname = "schedules/quickplanner

The window.location.search variable holds the part of the string that’s after the pathname.
That is, in the BART url above,

window.location.search = ?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 {
      query_string[pair[0]].push(pair[1]);
    }
  } 
  return query_string;
};

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s