js replaceall实现
在 JavaScript 中实现 replaceAll 功能
JavaScript 的 String.prototype.replace 方法默认只替换第一个匹配项。要实现替换所有匹配项的功能,可以通过以下几种方式:
使用正则表达式全局替换
const str = "apple banana apple";
const result = str.replace(/apple/g, "orange");
console.log(result); // "orange banana orange"
正则表达式中的 g 标志表示全局匹配。

使用 split 和 join 方法
const str = "apple banana apple";
const result = str.split("apple").join("orange");
console.log(result); // "orange banana orange"
这种方法通过分割字符串为数组后再合并,间接实现全部替换。
现代 JavaScript 中的 replaceAll 方法
ES2021 引入了原生 replaceAll 方法:

const str = "apple banana apple";
const result = str.replaceAll("apple", "orange");
console.log(result); // "orange banana orange"
此方法直接替换所有匹配的子字符串,无需使用正则表达式。
处理特殊字符的情况
当替换字符串中包含特殊正则字符时,需要先转义:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const str = "a.b.c";
const escaped = escapeRegExp(".");
const result = str.replace(new RegExp(escaped, 'g'), "-");
console.log(result); // "a-b-c"
性能考虑
对于简单替换,split + join 通常性能最好。复杂替换建议使用正则表达式或原生 replaceAll。






