您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

javascript在IE下trim函数无法使用的解决方法

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 本文实例分析了javascript在IE下trim函数无法使用的解决方法,对于web前段设计有一定的借鉴价值。具体分析如下:

首先,javascript的trim函数在firefox下面使用没有问题:

1 <script language="javascript">  2  var test1 = "  aa  ";  3  test1 = test1.toString();  4  test1 = test1.trim();  5 </script>

在火狐下这样用没有问题, 但是在IE下就报错!

对此,我们可以修改一下:

1 String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");}

在头上加上这一句,上面的就可以在IE和FF下都可以运行了:

  1 <script language="javascript">  2  String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");}  3  var test1 = "  aa  ";  4  test1 = test1.toString();  5  test1 = test1.trim();  6 </script>

JQuery提供的方法:

  01 <!DOCTYPE html>   02 <html>   03 <head>   04  <script src="http://code.jquery.com/jquery-latest.js"></script>   05 </head>   06 <body>   07  <button>Show Trim Example</button>   08 <script>   09 $("button").click(function () {   10 var str = "   lots of spaces before and after   ";   11 alert("'" + str + "'");   12 str = jQuery.trim(str);   13 alert("'" + str + "' - no longer");   14 });   15 </script>   16 </body>   17 </html>