Wednesday, September 12, 2012

trim() function does not work in IE

For IE the trim function is not built into the String Object. So if you try to do something like:
var str="Hello  ";
str.trim()

IE will throw an error like “Object doesn’t support this property or method”.

Here is the fix for that:


// Adding trim function to String object
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

The code above first checks if trim function is available in the String Object. we need to check this because trim function is available for Firefox and Chrome.

The above code needs to be executed before you call the first trim function.