把字符串里所有匹配到的地方都换成新内容。replace 默认只换第一个。
| 以前 · replace 只换第一个 | 现在 · replaceAll 一次全换 |
|---|---|
let str = "Hello, world! world, Hello!";
console.log(str.replace("world", "Universe"));
// Hello, Universe! world, Hello!
// (只换了第一个)
// 想全换,以前要写正则
console.log(str.replace(/world/g, "Universe"));
// Hello, Universe! Universe, Hello!
|
let str = "Hello, world! world, Hello!";
console.log(str.replaceAll("world", "Universe"));
// Hello, Universe! Universe, Hello!
// (一次全换,不用正则)
|
replace 默认只换第一处;replaceAll 直接全换,不用再写 /g 正则。
let str = "a b a b a b";
str.replaceAll(/a/g, "X"); // 可以(带 g,全换)
str.replaceAll("a", "X"); // 可以(直接传字符串)
str.replaceAll(/a/, "X"); // 报错(正则没带 g)
用 replaceAll 传正则,必须带 g,不然它不知道你要换几个。