Javascript trim() 函数在 IE8 中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11219731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:58:52  来源:igfitidea点击:

trim() function doesn't work in IE8?

javascriptinternet-explorerinternet-explorer-8

提问by Mukul

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

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

Object doesn't support this property or method

对象不支持此属性或方法

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

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

回答by nemo

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

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

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

回答by Karesh A

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

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

$.trim("  hello ");

give you

给你

"hello"

回答by dav_i

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

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

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

作为参考,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, '');
    };
  })();
}

and the supportfor it is:

对它的支持是:

+--------+---------+----+-------+--------+
| Chrome | Firefox | IE | Opera | Safari |
+--------+---------+----+-------+--------+
| All    | 3.5     |  9 | 10.5  |      5 |
+--------+---------+----+-------+--------+

回答by Amit Bhagat

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

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

if(typeof String.prototype.trim !== 'function') {
     String.prototype.trim = function(){
        return jQuery.trim( this );
    }
}