29

Whenever I use the trim() function on a string, it works fine with Chrome and Firefox but I get an error in IE8 saying :

Object doesn't support this property or method

Can anyone tell me why this happens and if there is a work around?

dav_i
  • 27,509
  • 17
  • 104
  • 136
Mukul
  • 355
  • 1
  • 3
  • 8
  • http://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie – ShaggyInjun Jun 27 '12 at 05:09
  • 1
    It's simple, IE8 doesn't support it: http://kangax.github.com/es5-compat-table/ – elclanrs Jun 27 '12 at 05:08
  • this link is helpful for this bug. [http://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie][1] [1]: http://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie – manish nautiyal Jan 16 '14 at 09:42

4 Answers4

85

IE8 doesn't support the trim function. Here's a polyfill:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  };
}
Charlie
  • 8,530
  • 2
  • 55
  • 53
nemo
  • 1,675
  • 10
  • 16
  • Can you explain what this code snippet is doing?, mainly, what this if statement is about. – dwjohnston Mar 17 '14 at 02:13
  • 3
    This snippet first checks if the trim function is defined (typeof String.prototype.trim !== 'function') If it is not defined, it defines the function which is a simple replace with a regular expression – nemo Mar 17 '14 at 12:00
39

if you want you can add jquery and use $.trim(....) this will work..

$.trim("  hello ");

give you

"hello"
Karesh A
  • 1,731
  • 3
  • 22
  • 47
  • 2
    Thanks for this answer - much preferred for sites that are already using jQuery. – rcourtna Apr 02 '13 at 19:55
  • 1
    No offense, but I think this should be done only when we are already using javascript. Other wise adding jquery to the site only for one function does not look good. The above solution looks more elegant. – Siddhant Swami Jul 30 '14 at 06:07
3

Internet Explorer only started support for trim() from version 9.

For reference, the MDN Polyfill for String.prototype.trim() is:

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

and the support for it is:

+--------+---------+----+-------+--------+
| Chrome | Firefox | IE | Opera | Safari |
+--------+---------+----+-------+--------+
| All    | 3.5     |  9 | 10.5  |      5 |
+--------+---------+----+-------+--------+
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

Since, I was using jQuery, with the help of @nemo and @karesh-a I came up with:

if(typeof String.prototype.trim !== 'function') {
     String.prototype.trim = function(){
        return jQuery.trim( this );
    }
}
Amit Bhagat
  • 4,182
  • 3
  • 23
  • 24