在 Firefox 裡這樣寫完全正常:
<script language="javascript"> var test1 = " aa "; test1 = test1.toString(); test1 = test1.trim(); </script>
但換到舊版 IE 就會直接拋出錯誤,因為那個年代的 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>
建議加上條件判斷 if (!String.prototype.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>
如果專案本來就載入了 jQuery,直接借用 jQuery.trim() 最省事。值得一提的是,今日的專案幾乎不必再煩惱這個問題——所有現代瀏覽器都已原生支援 trim,這類相容處理主要是維護老系統時才需要。