trim() function doesn't work in IE8?

2019-02-01 22:50发布

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?

4条回答
来,给爷笑一个
2楼-- · 2019-02-01 22:57

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

$.trim("  hello ");

give you

"hello"
查看更多
聊天终结者
3楼-- · 2019-02-01 23:05

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 );
    }
}
查看更多
相关推荐>>
4楼-- · 2019-02-01 23:14

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, ''); 
  };
}
查看更多
可以哭但决不认输i
5楼-- · 2019-02-01 23:21

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 |
+--------+---------+----+-------+--------+
查看更多
登录 后发表回答