Parsing a URL Querystring with Javascript

Can you access a URL querystring with Javascript?
Yes. Just refer to location.search.

Why would you want to reference the URL querystring with Javascript?
A couple reasons come to mind.

  • Highlighting a specified term wherever it appears within a page
  • Linking to a dynamic page in a specific state

The latter, which I have also seen called deep linking, seems particularly useful to me. You want to send someone a link to a video, but it’s one of several videos in a playlist on a page. You can send the URL and tell them, “It’s the 4th video from the top.”

Or you want to send someone the link to a page featuring one of the nearly-ubiquitous carousels, like the Discovery Channel’s main page. You want to send a link to the lunar rover feature, but by default the page features a ridiculous-looking reality show called American Choppers.

One way would be to supply the user with a link, something like:
http://dsc.discovery.com/?feature=4

(Sure, you could link to the feature’s destination page, but humor me here.)

Here’s some code to help turn location.search into something a little easier to use:

function parseQS() {
	// Remove leading question mark ("?") and split into array of key/value pairs
	var qsArray = location.search.slice(1).split("&");
	// Initialize object to store key/value pairs
	var json = {};
	// Loop through key/value pairs and separate into keys and values
	for ( var i = 0; i < qsArray.length; i++ ) {
		var kv = qsArray[i].split("=");
		var key = kv[0];
		var val;
		if ( kv.length == 1 ) val = key;
		// A key may be present without a value, so set a placeholder value
		else val = kv[1];
		json[key] = val;
	}
	return json;
}

Now you can check to see if parseQS().feature is defined, and if so, show the user the specified feature.

I’m sure someone has created a more elegant Javascript querystring parser. If you’ve found one–or if you wrote one–let me know in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *