JavaScript 的 trim() 在 Firefox 下使用完全沒問題:
<script language="javascript">
var test1 = " aa ";
test1 = test1.toString();
test1 = test1.trim();
</script>
同樣的程式碼放到舊版 IE 卻會直接報錯——因為 IE 的 String 原型上根本沒有這個方法。
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*$) 少了反斜線,s 會被當成普通字母而非空白字元,結果完全削不掉空格。正確應為 \s,在 HTML 或某些編輯器中還要留意反斜線是否被吃掉。
實務上通常會一次補齊三個方法:
if (!String.prototype.trim) {
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g, "");
};
}
if (!String.prototype.ltrim) {
String.prototype.ltrim = function(){
return this.replace(/^\s+/g, "");
};
}
if (!String.prototype.rtrim) {
String.prototype.rtrim = function(){
return this.replace(/\s+$/g, "");
};
}
加上 if (!String.prototype.trim) 的判斷很重要:在已原生支援的環境中就保留瀏覽器的實作,通常效能更好,也避免覆蓋掉可能已被其他函式庫擴充的版本。
那麼直接用 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>
當然,在支援 ES5 以上的環境裡,str.trim() 本來就是標準方法,上面這些 polyfill 只有在維護老系統時才需要。