js 实现replaceall
JavaScript 实现 replaceAll 方法
JavaScript 字符串原生 replace 方法默认只替换第一个匹配项。要实现替换所有匹配项,可通过以下方式:
使用正则表达式全局匹配
const str = "apple orange apple";
const result = str.replace(/apple/g, "banana");
console.log(result); // "banana orange banana"
使用 split 和 join 组合
const str = "apple orange apple";
const result = str.split("apple").join("banana");
console.log(result); // "banana orange banana"
ES2021 新增的 replaceAll
现代浏览器支持原生 replaceAll 方法:
const str = "apple orange apple";
const result = str.replaceAll("apple", "banana");
console.log(result); // "banana orange banana"
兼容性处理方案
如需兼容旧环境,可添加 polyfill:
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replacement) {
return this.split(search).join(replacement);
};
}
特殊字符处理
当替换内容包含正则特殊字符时,需先转义:

function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const str = "1+1=2";
const result = str.replace(new RegExp(escapeRegExp("1+1"), 'g'), "2+2");
console.log(result); // "2+2=2"






