javascript在IE下trim函數無法使用的解決方案

來源:互聯網
上載者:User

javascript在IE下trim函數無法使用的解決方案

 本文執行個體分析了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>

在Firefox下這樣用沒有問題, 但是在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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.