萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

解決 IE 瀏覽器下 String.trim() 不支持的兼容性方案

問題背景

String.prototype.trim() 是 ES5 標準方法,IE 8 及以下版本不支持。直接調用會拋出 "Object doesn't support this property or method" 錯誤。

方案一:Polyfill 修補原型(推薦)

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 更完整
  • 放在項目入口文件最頂部,確保全局生效

方案二:使用 jQuery $.trim()(若已引入 jQuery)

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);      // ""

適合不想修改內置對象、或需處理非字符串輸入的場景。

現代瀏覽器原生擴展:trimStart / trimEnd

'  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+ 特性的兼容性,避免手動維護零散補丁。

copyright © 萬盛學電腦網 all rights reserved