欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-11 18:38:07
...

本文翻译自:.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/ )。