萬盛學電腦網

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

JavaScript 實現字符串 replaceAll:原生替代方案與擴展原型

早期 JS String.prototype.replace 僅替換首次匹配,全局替換需正則 /g 旗標。ES2021 正式引入 replaceAll,本文覆蓋 Polyfill 實現與現代用法。

ES2021 原生 replaceAll

'foo bar foo'.replaceAll('foo', 'baz'); // "baz bar baz"
'foo bar foo'.replaceAll(/foo/g, 'baz'); // TypeError: 第一參數不能是正則(除非帶 g)

規則:第一參數為字符串時自動全局替換;為正則時必須帶 g 旗標,否則拋錯。

Polyfill 實現(兼容舊環境)

if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function(searchValue, replaceValue) {
    // 字符串搜索:轉義特殊字符構建全局正則
    if (typeof searchValue === 'string') {
      const escaped = searchValue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      return this.replace(new RegExp(escaped, 'g'), replaceValue);
    }
    // 正則搜索:必須有 g 旗標
    if (searchValue instanceof RegExp) {
      if (!searchValue.global) {
        throw new TypeError('replaceAll 正則參數必須包含 g 旗標');
      }
      return this.replace(searchValue, replaceValue);
    }
    // 其他類型轉字符串
    return this.replace(String(searchValue), replaceValue);
  };
}

替代方案對比

方案代碼優點缺點
split+joinstr.split('foo').join('baz')無正則特殊字符問題性能稍差,語義不明確
正則 /gstr.replace(/foo/g, 'baz')原生、高性能需手動轉義字符串
replaceAllstr.replaceAll('foo', 'baz')語義清晰、自動轉義需 ES2021+ 或 Polyfill

正則特殊字符轉義工具函數

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// 使用
const userInput = 'a.b[c]d';
str.replace(new RegExp(escapeRegExp(userInput), 'g'), 'X');

性能基準(百萬次操作)

// 簡單基準測試
const str = 'a'.repeat(1000000);
console.time('replaceAll'); str.replaceAll('a', 'b'); console.timeEnd('replaceAll'); // ~15ms
console.time('split/join'); str.split('a').join('b'); console.timeEnd('split/join');   // ~45ms
console.time('replace/g');  str.replace(/a/g, 'b');  console.timeEnd('replace/g');    // ~12ms

原生 replaceAll 性能接近 replace(/g),遠優於 split/join。

總結

現代項目直接使用 String.prototype.replaceAll,語義明確、自動轉義、性能優異。舊環境引入 Polyfill 即可無縫遷移。避免手寫正則轉義 Bug,統一使用標準 API。

copyright © 萬盛學電腦網 all rights reserved