JavaScript原生String.prototype.replace()僅替換首次匹配,全局替換需配合正則/g標誌。本文提供通用replaceAll封裝,分析eval動態構建正則的風險,並推薦現代ES2021標準String.prototype.replaceAll()。
function replaceAll(obj, str1, str2) {
// 風險:eval執行任意代碼,若str1含特殊字符可能注入
var result = obj.replace(eval("/" + str1 + "/gi"), str2);
return result;
}
// 使用
alert(replaceAll("111,222,333", ",", "|")); // "111|222|333"
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function replaceAllSafe(str, search, replacement) {
var regex = new RegExp(escapeRegExp(search), 'gi');
return str.replace(regex, replacement);
}
// 瀏覽器支援:Chrome 85+, Firefox 77+, Safari 13.1+, Edge 85+
"111,222,333".replaceAll(",", "|"); // "111|222|333"
// 無需正則轉義,直接按字面量全量替換
// 不支援正則表達式參數,純字符串匹配
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replace) {
if (search instanceof RegExp) throw new TypeError("replaceAll不支援正則");
return this.split(search).join(replace);
};
}
| 方法 | 長字符串(10萬字符)耗時 | 備註 |
|---|---|---|
split/join | ~2ms | 最快,無正則開銷 |
replace(/regex/g) | ~5ms | 需預編譯正則 |
replaceAll (原生) | ~3ms | 引擎優化,推薦首選 |
str.replaceAll(search, replace)split/join polyfilleval動態構建正則—— XSS風險、性能差、難維護const regex = new RegExp(escapeRegExp(str), 'g')複用