11 April, 2006

split and regexp crossbrowser issue

Regexp are very powerfull when it comes to going deeper in string manipulation. However, in some cases, Internet Explorer and Firefow doesn't implement them strictly the same way. My best example is the following :
You want to split a string with several separators. This is well illustrated when splitting a date to get day, month, year and time info.
A Date in javascript prints as : Tue Apr 11 2006 17:15:27 GMT+0200
If you want to get all the infos, you can make:

var dateInfos = (new Date()).toString().split(/ GMT|[ :]/);
var day = dateInfos[0];
var month = dateInfos[1];
var date = dateInfos[2];
var year = dateInfos[3];
var hour = dateInfos[4];
var minute = dateInfos[5];
var second = dateInfos[6];
var offsetUTC = dateInfos[7];

So you get all the infos in one shot! This works with IE or Firefox.
Now imagine the first caracter of the splitted string is a separator:

var dateInfos = (' '+(new Date()).toString()).split(/ GMT|[ :]/);
var day = dateInfos[0];
var month = dateInfos[1];
var date = dateInfos[2];
var year = dateInfos[3];
var hour = dateInfos[4];
var minute = dateInfos[5];
var second = dateInfos[6];
var offsetUTC = dateInfos[7];

In this case, dateInfos[0] is empty in Firefox and 'Tue' is in dateInfos[1].
In IE, it remains the same as before, namely 'Tue' is in dateInfos[0].
And subsequently, the dateInfos Array is one element longer on Firefox than on IE.
So be carefull when you play with RegExp!
My best hack would be to ensure that the firsts caracters of the string are not a separator.

1 comment:

Steve said...

See this page for a way to fix String.split() to return the same, correct results in all browsers: http://blog.stevenlevithan.com/javascript/cross-browser-split/