I have a string which needs to be split by three underscore characters. An example of the string might be:
var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array";
So I use the Split() function. Fine in everything but IE8 (and probably 7 too but not tried) which gives an “Object doesn’t support this property or method” error if the string doesn’t contain those characters. So I found another post which said to check that the underscore characters appear in the string before splitting, so I do this:
if (stringItemsPlanner.indexOf('___') == -1){
arrItemsPlanner = [];
}else{
arrItemsPlanner = stringItemsPlanner.split('___');
}
But now this errors too because apparently IE8 doesn’t support ‘indexOf’.
After a lot of searching I’ve tried adding some code to the top of my script to act as a ‘polyfil’ for this method:
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)? Math.ceil(from) : Math.floor(from);
if (from < 0){
from += len;
for (; from < len; from++){
if (from in this && this[from] === elt){
return from;
}
return -1;
};
}
}
}
But still no joy.
I’m now past the point of frustration and can’t really think of any other way to get this simple thing to work.
Can anyone shed any light on this or think of an alternative way to safely split a string to an array in a way that works cross-browser? It’s got to be simple but I just can’t think straight now.
Thanks all!
Have a look here
http://jsfiddle.net/mplungjan/Bnx6m/