Welcome 微信登录

首页 / 脚本样式 / JavaScript / javascript在IE下trim函数无法使用的解决方法

本文实例分析了javascript在IE下trim函数无法使用的解决方法,对于web前段设计有一定的借鉴价值。具体分析如下:
首先,javascript的trim函数在firefox下面使用没有问题:
<script language="javascript">var test1 = "aa";test1 = test1.toString();test1 = test1.trim(); </script>
在火狐下这样用没有问题, 但是在IE下就报错!
对此,我们可以修改一下:
String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");} 
在头上加上这一句,上面的就可以在IE和FF下都可以运行了:
<script language="javascript">String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");}var test1 = "aa";test1 = test1.toString();test1 = test1.trim(); </script> 
JQuery提供的方法:
<!DOCTYPE html><html><head> <script src="http://code.jquery.com/jquery-latest.js"></script></head><body> <button>Show Trim Example</button><script>$("button").click(function () {var str = " lots of spaces before and after ";alert(""" + str + """);str = jQuery.trim(str);alert(""" + str + "" - no longer");});</script></body></html>
相信本文所述对大家利用javascript进行WEB前端浏览器的兼容性设计有不错的借鉴价值。