我试图在我的一个JavaScript程序中应用.trim()到字符串。它在Mozilla下运行良好,但在IE8中尝试时显示错误。有人知道这是怎么回事吗?有没有办法我可以让它在IE中工作?

代码:

var ID = document.getElementByID('rep_id').value.trim();

错误显示:

Message: Object doesn't support this property or method
Line: 604
Char: 2
Code: 0
URI: http://test.localhost/test.js

当前回答

var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}

其他回答

添加以下代码向字符串添加修饰功能。

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

jQuery:

$.trim( $("#mycomment").val() );

有人使用$("#mycomment").val().trim();但这在IE上行不通。

刚刚发现IE停止支持trim(),可能是在最近的windows更新之后。如果你使用dojo,你可以使用dojo.string.trim(),它可以跨平台工作。

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim

这是javascript最近添加的功能,IE不支持。

我认为JavaScript标准中没有原生的trim()方法。也许Mozilla提供了一个,但如果你想在IE中使用,你需要自己编写。本页上有几个版本。