JavaScript中的replaceAll方法用于替换字符串中所有匹配项,原生支持ES2025及以上版本,如'hello world hello'.replaceAll('hello', 'hi')返回"hi world hi";对于不支持环境,可通过转义特殊字符并结合正则全局替换实现polyfill,需注意输入类型检查及避免直接使用未转义字符串作为正则。
JavaScript 中的 replaceAll 方法用于将字符串中所有匹配的子串替换为指定内容。在较新的 JavaScript 版本(ES2025)中,String.prototype.replaceAll 已被原生支持。但如果你需要在不支持该方法的环境中使用,可以手动实现。
'hello world hello'.replaceAll('hello', 'hi') 返回 "hi world hi"

使用 String.prototype.replace 配合正则表达式全局替换:
示例代码:
function replaceAll(str, find, replacement) { // 转义字符串中的正则特殊字符 const escapedFind = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return str.replace(new RegExp(escaped7Find, 'g'), replacement); }find 是字符串,可以直接这样做:str.replace(new RegExp(find.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replacement)
基本上就这些,现代浏览器已普遍支持原生 replaceAll,老环境可用 polyfill 方案平滑过渡。