我试图在我的一个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

当前回答

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

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

其他回答

jQuery:

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

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

这是因为输入错误getElementByID。将其更改为getElementById

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

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

看起来这个函数在IE中没有实现。如果你正在使用jQuery,你可以使用$.trim()来代替(尽管在jQuery 3.5已经弃用了)。

不幸的是,trim()不支持跨浏览器JavaScript。

如果你不使用jQuery(它有.trim()方法),你可以使用以下方法来添加对字符串的修剪支持:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}