早期 JS String.prototype.replace 僅替換首次匹配,全局替換需正則 /g 旗標。ES2021 正式引入 replaceAll,本文覆蓋 Polyfill 實現與現代用法。
'foo bar foo'.replaceAll('foo', 'baz'); // "baz bar baz"
'foo bar foo'.replaceAll(/foo/g, 'baz'); // TypeError: 第一參數不能是正則(除非帶 g)
規則:第一參數為字符串時自動全局替換;為正則時必須帶 g 旗標,否則拋錯。
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+join | str.split('foo').join('baz') | 無正則特殊字符問題 | 性能稍差,語義不明確 |
| 正則 /g | str.replace(/foo/g, 'baz') | 原生、高性能 | 需手動轉義字符串 |
| replaceAll | str.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。