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

Muk*_*kul 28 javascript internet-explorer internet-explorer-8

每当我trim()在字符串上使用该函数时,它适用于Chrome和Firefox,但我在IE8中收到错误说:

Object不支持此属性或方法

任何人都可以告诉我为什么会发生这种情况,如果有解决方法吗?

nem*_*emo 83

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

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

  • 这个片段首先检查是否定义了trim函数(typeof String.prototype.trim!=='function')如果没有定义它,它定义了一个简单替换正则表达式的函数 (3认同)

Kar*_*h A 39

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

$.trim("  hello ");
Run Code Online (Sandbox Code Playgroud)

给你

"hello"
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答 - 对于已经使用jQuery的网站更受青睐. (2认同)