JavaScript中的.trim()无法在IE中运行

本文翻译自:.trim() in JavaScript not working in IE

I tried to apply .trim() to a string in one of my JavaScript programs. 我尝试将.trim()应用于我的一个JavaScript程序中的字符串。 It's working fine under Mozilla, but an error displays when I try it in IE8. 它在Mozilla下工作正常,但是当我在IE8中尝试它时会显示错误。 Does anyone know what is going on here? 有谁知道这里发生了什么? Is there anyway I can make it work in IE? 无论如何我可以在IE中使用吗?

code: 码:

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

error display: 错误显示:

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

#1楼

参考:https://stackoom.com/question/9gRy/JavaScript中的-trim-无法在IE中运行


#2楼

I have written some code to implement the trim functionality. 我编写了一些代码来实现修剪功能。

LTRIM (trim left): LTRIM (左侧饰边):

function ltrim(s)
{
    var l=0;
    while(l < s.length && s[l] == ' ')
    {   l++; }
    return s.substring(l, s.length);
} 

RTRIM (trim right): RTRIM (右侧饰边):

function rtrim(s)
{
    var r=s.length -1;
    while(r > 0 && s[r] == ' ')
    {   r-=1;   }
    return s.substring(0, r+1);
 }

TRIM (trim both sides): TRIM (两边修剪):

function trim(s)
{
    return rtrim(ltrim(s));
}

OR 要么

Regular expression is also available which we can use. 我们也可以使用正则表达式。

function trimStr(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

Useful Explanation 有用的解释


#3楼

I had the same problem in IE9 However when I declared the supported html version with the following tag on the first line before the 我在IE9中遇到了同样的问题然而当我在第一行之前声明支持的html版本时带有以下标记

<!DOCTYPE html>
<HTML>
<HEAD>...
.
.

The problem was resolved. 问题解决了。


#4楼

I don't think there's a native trim() method in the JavaScript standard. 我认为JavaScript标准中没有原生的trim()方法。 Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. 也许Mozilla提供一个,但如果你想在IE中使用一个,你需要自己编写。 There are a few versions on this page . 此页面上有几个版本。


#5楼

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

This is a pretty recent addition to javascript, and its not supported by IE. 这是javascript的最新补充,IE不支持。


#6楼

It looks like that function isn't implemented in IE. 看起来IE中没有实现该功能。 If you're using jQuery, you could use $.trim() instead ( http://api.jquery.com/jQuery.trim/ ). 如果您使用的是jQuery,则可以使用$.trim()代替( http://api.jquery.com/jQuery.trim/ )。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值