28

每当我trim()在字符串上使用该函数时,它在 Chrome 和 Firefox 上都能正常工作,但在 IE8 中出现错误:

对象不支持此属性或方法

谁能告诉我为什么会发生这种情况以及是否有解决方法?

4

4 回答 4

84

IE8 不支持修剪功能。这是一个polyfill:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  };
}
于 2012-06-27T05:14:48.920 回答
39

如果你愿意,你可以添加 jquery 并使用 $.trim(....) 这将工作..

$.trim("  hello ");

给你

"hello"
于 2012-06-27T05:11:10.370 回答
2

trim()Internet Explorer 仅从版本 9开始支持。

作为参考,MDN PolyfillString.prototype.trim()是:

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, '');
    };
  })();
}

对它的支持是:

+--------+---------+----+-------+--------+
| Chrome | Firefox | IE | Opera | Safari |
+--------+---------+----+-------+--------+
| All    | 3.5     |  9 | 10.5  |      5 |
+--------+---------+----+-------+--------+
于 2015-03-12T16:10:13.700 回答
0

因为,我在使用 jQuery,在 @nemo 和 @karesh-a 的帮助下,我想出了:

if(typeof String.prototype.trim !== 'function') {
     String.prototype.trim = function(){
        return jQuery.trim( this );
    }
}
于 2017-03-05T09:46:54.860 回答