25 Oct

ie vs regexps as hash array indexes

Cryptic, right?

I have a small piece of javascript which looks a bit like this:

	var kaejax_replaces={'([89A-F][A-Z0-9])':'%u00$1','22':'"','2C':',','3A':':','5B':'[','5D':']','7B':'{','7D':'}'};
		for(var a in kaejax_replaces){
			delete kaejax_replaces[a];

What that does is to build up an array (or Object, to be precise) called kaejax_replaces. A context for this is that you should escape() post_data before you send it via AJAX, but for some characters, the escape() is not necessary, so to save bandwidth (and thereby speed up the application), we convert those characters back by looping through the kaejax_replaces array before sending off the post_data:

function kfm_sanitise_ajax(d){
	var r=kaejax_replaces;
	for(var a in r)d=d.replace(r[a],a);
	return d;

In the above, d is the data to be sanitised of extraneous conversion.

Now, the problem arises that an object such as the following is actually illegal in IE (who knows why…):

		/%([89A-F][A-Z0-9])/g:	'%u00$1',
		/%22/g:			'"',
		/%2C/g:			',',
		/%3A/g:			':',
		/%5B/g:			'[',
		/%5D/g:			']',
		/%7B/g:			'{',
		/%7D/g:			'}'

Now, I /like/ that code. it’s short, neat, and does the job efficiently.

Unfortunately, IE is a bugger, so we need to do it the old primitive way…

	var kaejax_replaces_regexps=[],kaejax_replaces_replacements=[];
	for(var i in kaejax_replaces){
	function kfm_sanitise_ajax(d){
		for(var a in window.kaejax_replaces_regexps)d=d.replace(kaejax_replaces_regexps[a],kaejax_replaces_replacements[a]);
		return d;

That is all.

ps: IE sucks – the above article is also true of IE7

%d bloggers like this: