replaceAll 一次性替换所有匹配,不用写正则全局标记。
核心用法:
① str.replaceAll("旧", "新")——替换全部
② 老写法 replace 只能替换第一个,要加 /g
坑:replaceAll 第二个参数是字符串不是函数、老浏览器不支持、跟正则 /g 效果一样。
同一个句子里有两个 world,replace 只把第一个换掉,第二个原地不动;replaceAll 把所有 world 一起换掉。
// 一句里有两个 world
let str = "Hello, world! world, Hello!";
// replace:只换第一个
// 只换掉第一个
console.log(str.replace("world", "Universe"));
// Hello, Universe! world, Hello! ← 第二个 world 还在
// 想全换,以前要写正则 + /g
// 正则加 g 才全换
console.log(str.replace(/world/g, "Universe"));
// Hello, Universe! Universe, Hello! ← 两个都换了
// replaceAll:一次全换,不用正则
// 传字符串就自动全换
console.log(str.replaceAll("world", "Universe"));
// Hello, Universe! Universe, Hello!
replaceAll 传普通字符串永远安全;但如果传的是正则,就必须带全局标志 g,否则直接报错。
// 一个里有 3 个 a
let str = "a b a b a b";
// 可以(正则带了 g)
str.replaceAll(/a/g, "X");
// 可以(传字符串,自动全换)
str.replaceAll("a", "X");
// ★ 报错(正则没带 g)
str.replaceAll(/a/, "X");
如果你给 replaceAll 传了一个不带 g 的正则,浏览器会直接抛 TypeError。因为它怕你以为"全换了"结果只换一个——所以干脆报错提醒。传字符串就没这个问题。
把模板里的 {name}、{amount} 一个个替换成真实值,链式调用就行。
// 带占位符的模板
let tpl = "订单 {name} 已支付,金额 {amount} 元";
// 开始填
let filled = tpl
// 把所有 {name} 换掉
.replaceAll("{name}", "大喇叭")
// 把所有 {amount} 换掉
.replaceAll("{amount}", "99");
// 打印填好的字符串
console.log(filled);
// 订单 大喇叭 已支付,金额 99 元
替换所有占位符、清洗敏感词、把 \r\n 统一成 \n——凡是"所有匹配都换"的场景,replaceAll 都比正则 /g 更直白,新手也一眼能看懂。
① 可能在什么地方用:填充模板占位符、用户输入敏感词过滤、统一换行符 \r\n → \n、批量替换文案里的错别字。
② 常见的问题:用 replace 只换了第一个没发现;给 replaceAll 传不带 g 的正则直接报错;以为 replaceAll 会改原字符串(其实它返回新字符串)。
③ 解决思路:要全换就用 replaceAll 传字符串;它返回新串,要接回变量;传正则就记得末尾加 /g。
| API | 作用 | 参数 | 返回值 | 代码示例 |
|---|---|---|---|---|
| str.replace(a, b) | 默认只换第一个就停手 | 旧内容, 新内容 | 新字符串 | str.replace("a", "b"); |
| str.replaceAll(a, b) | 把所有匹配的全换掉 | 旧内容, 新内容 | 新字符串 | str.replaceAll("a", "b"); |