我试图在我的一个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
不幸的是,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+$/,"");
}