Friday, June 25, 2010

Google Analytics Custom Variables - How To Trim Properly

Well I've been geeking out with Google Analytics as of late, and I've got to say, why would anyone pay for it anymore? Awesome tool that satisfies most Analytics needs.

That being said, recently Google launched a new feature called Custom Variables. This new feature is very powerful, but it has some limitations. One of these is that during a single page load request, if you total up all the keys and all the values for your request, they can only equal 64 bytes in total.

Other limitation are that you are limited to setting 5 key value pairs at a time, and the other limitation I have run up against is that you cannot send multiple values for a single key in a single page load.

But wait there's more.... The 64 character limit is URIEncoded, that is to say if you have a string with a character that gets URIEncoded, say like a semi-colon, this single byte will be expanded to 3 bytes when it gets URIEncoded.

So AB;

Becomes

AB%3D

If you are using the code on the net I found that URIEncodes, then trims the string, then URIDecodes before passing to _setCustomVar, you can run into an error where you wind up with a partial string on the end, that when URIDecoded will generate an error. To solve this problem I wrote the following function that allows the setting of custom variables and will trim them to an arbitrary length and will also get rid of any partially URIEncoded strings at the end.

Enjoy:

  function gaTrimCustomVar(vstr,vlen) {
// URI encode and truncate to vlen
var tstr = encodeURIComponent(vstr).substr(0,vlen);

// If the first character is URL encoded and length is not at least 3
// we'll return untrimmed and let the upper level deal otherwise we would clear
// the value completely and return an empty string.
if( tstr.indexOf('%') == 0 && vlen < 3) {
return vstr;
}

// load a pointer to any partial URI encoded characters at the end

var uptr = tstr.substr(tstr.length - 2,2).indexOf('%');

// If there aren't any partial URI encoded characters at the end, return
if(uptr == -1) {
return decodeURIComponent(tstr);
}

// return only up to the last partially URI encoded character.
return decodeURIComponent(tstr.substr(0,(tstr.length - 2) + 1));

}

2 comments:

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.

GeekTravels said...

No worries. If you need more details post your comments here, and I'll do my best to answer, that way everyone can benefit.

Glad this was of help. I found this when testing some data and turns out this API is still a bit clunky, but getting better.