Thursday, October 10, 2013

String.split() issue in IE8

String.split() behaves differently in IE8 and Chrome/FF when the delimiter used is a regex. In Chrome/FF this method returns an array of all the tokens and the strings that qualified as delimiters in proper order. In IE8 it returns only an array of tokens (the delimiter strings are omitted)

For example

Input -->
String: The train starts from {%1}{%2n} at {%3} on {%4t, dd-MM-yyyy}
Delimiter Regex: ({.*?})

Output -->
Chrome/FF: ["The train starts from ", "{%1}", "", "{%2n}", " at ", "{%3}", " on ", "{%4t, dd-MM-yyyy}", ""]
IE8: ["The train starts from ", " at ", " on "]

To fix this IE8 anamoly I wrote a custom split method that returns delimiters strings as well. You can find it here:
http://jsfiddle.net/aneezbacker/3hyD8/7/ 

Its good for starters. Additional changes can be made to support regex modifiers.


BONUS: IE8 also doesn't support String.trim().  Add the following to your code to make it work
         
           // adding trim function if its not present (IE8 doesn't support trim)
           if(typeof String.prototype.trim !== 'function') {
                String.prototype.trim = function() {
                    return this.replace(/^\s+|\s+$/g, '');
                }
            }

Hope that helps :)

References:
http://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie