String.prototype.trim() 是 ES5 標準方法,IE 8 及以下版本不支持。直接調用會拋出 "Object doesn't support this property or method" 錯誤。
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
關鍵點:
if (!String.prototype.trim) 判斷,避免覆蓋原生實現\uFEFF (BOM) 和 \xA0 (不換行空格),比單純 \s 更完整var str = ' hello world ';
var trimmed = $.trim(str); // "hello world"
// 或原生調用(jQuery 內部實現同上)
var trimmed2 = jQuery.trim(str);
jQuery 內部同樣做了兼容性處理,且處理了 null/undefined 邊界情況。
var utils = {
trim: function (str) {
if (str == null) return '';
return String(str).replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
};
utils.trim(' abc '); // "abc"
utils.trim(null); // ""
適合不想修改內置對象、或需處理非字符串輸入的場景。
' hello '.trimStart(); // "hello "
' hello '.trimEnd(); // " hello"
' hello '.trim(); // "hello"
ES2019 引入,IE 完全不支持,現代項目可配合 Polyfill 使用。
<script>
// 1. Polyfill
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
// 2. 測試
var testCases = [
' normal ',
'\t\\n\\r mixed \\t',
'\uFEFF\xA0 unicode spaces \uFEFF\xA0',
'',
'no-spaces'
];
testCases.forEach(function (s) {
console.log('["' + s.trim() + '"]');
});
// 3. 兼容 IE8 的寫法(不使用 forEach)
for (var i = 0; i < testCases.length; i++) {
console.log(i + ': [' + testCases[i].trim() + ']');
}
</script>
| 誤區 | 正確做法 |
|---|---|
用 /^\s+|\s+$/g 正則 | 漏匹配 BOM/NBSP,建議 /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g |
直接賦值 String.prototype.trim = ... 不判斷 | 覆蓋原生實現可能導致性能下降或行為差異 |
以為 $.trim() 只能在 jQuery 環境用 | 可單獨提取其實現代碼作為獨立工具函數 |
為 String.prototype.trim 打補丁是成本最低、侵入性最小的方案。現代項目建議直接使用 core-js 等成熟 Polyfill 庫,統一管理所有 ES5/ES6+ 特性的兼容性,避免手動維護零散補丁。