Feb
18
2009

Be Careful parsing your URL string with Javascript

…so I know you’ve looked around the net for a good method to parse URL variables with javascript, and I’m sure that you’ve found some elegant method that looks something like:

function parseLocation() {
	var turl = window.location.search;
	ar = turl.split('&');
	var b = {};

	for (var i = 0; i < ar.length; i++) {
		var c = ar[i].split('=');
		b[c[0]] = c[1];
	}
	return b;
}

and you’ve thought, “oh, look how nice and compact that is. I shall use it post-haste!” Well, let me, as Mr. Guy Who’s Gotten Plenty Of Grumpy Complaints About This, light a candle rather than curse your darkness.

It is a good method, don’t get me wrong. It works great in theory. The problem is, say you copy/paste you url into, say, your Blogging Software of choice*. It might then re-interpret your url from:

http://post-hipster.com/parsey.html?var1=hey&var2=mambo&var3=fagabefe

into

http://post-hipster.com/parsey.html?var1=hey&amp;var2=mambo&amp;var3=fagabefe

and, on some browsers*, no amount of encode() or decode() will make that go away, which, in essence, changes your parsed variable names int “amp;var2” and “amp;var3”

My solution, however inelegant, is to make the function explicitly look for the variables in question:

function parseLocation() {
	var turl = window.location.search;
	ar = turl.split('&');
	var b = {var1:'default_for_var1', var2:''};

	for (var i = 0; i < ar.length; i++) {
		var c = ar[i].split('=');
		if (c[0].indexOf('var1') > -1) {
			b['var1'] = c[1];
		} else if (c[0].indexOf('var2') > -1) {
			b['var2'] = c[1];
		} else if (c[0].indexOf('var3') > -1) {
			b['var3'] = c[1];
		}
	}
	return b;
}

I know, I coulda just RegEx’ed the ‘amp;’ away, but this way prevents any other encoding mishaps. If this was a global function, across a buncha different pages, I probably would just look for and get rid of the ‘amp;’

So there you go. Unfortunately, URL parsing isn’t always as nice as we want it  to be.

* unfortunately I can’t be more specific than this, because I haven’t yet been able to duplicate the error on any browser / os combination I’ve tried, but I’ve gotten enough complaints about it to know that it exists.

Share/Save

tags: ,
posted in ajax, coding, hackery, javascript by chip

Follow comments via the RSS Feed | Leave a comment

Leave Your Comment

 

 
Powered by Wordpress and MySQL. Theme by openark.org