DIV CSS 佈局教程網

解決 JavaScript 的 trim 函式在 IE 下無法使用的問題
編輯:關於JavaScript     

trim 函式用來去除字串前後的空白,但在舊版 Internet Explorer 中卻可能無法使用而報錯。本文分析這個問題並提供解法,對 Web 前端設計有不錯的參考價值。

首先,trim 在 Firefox 下使用是沒有問題的:

 <script language="javascript"> var test1 = " aa "; test1 = test1.toString(); test1 = test1.trim(); </script> 

但在 IE 下這樣寫就會報錯。對此,我們可以在使用之前先為 String 的 prototype 補上一個 trim 的實作:

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

加上這一句之後,上面的程式就能在 IE 和 Firefox 下都正常運行了:

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

這裡的正則 /(^\s*)|(\s*$)/g 用來比對字串開頭與結尾的空白並替換掉,是一種典型的 polyfill(相容補丁)寫法。

另外,如果你的專案已經引入 jQuery,也可以直接用 jQuery 提供的 jQuery.trim():

 <!DOCTYPE html> <html> <head> <script src="https://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> 

無論是用 polyfill 自行補實作,還是直接呼叫 jQuery.trim,都能優雅地解決 IE 下 trim 無法使用的相容問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved