replaceAll(search, replaceWith)
会用replaceWith
替换所有的search
。
然后,确保你有一个字符串,将一种引号用另一种引号包裹:
"a 'b' c".replaceAll("'", '"')
// result: "a "b" c"
"a 'b' c".replaceAll(`'`, `"`)
// result: "a "b" c"
更多关于replaceAll
replaceAll (MDN): replaceAll(search, replaceWith)
实际上,它与使用全局正则表达式的replace()
相同,只是在我看来,replaceAll()
更易读。
(*) 意味着它将匹配所有出现的实例。
示例1 - 使用字符串进行搜索
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
console.log(p.replaceAll('2020', '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
例子2 - 使用正则表达式进行搜索
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
const regex = /2020/gi
console.log(p.replaceAll(regex, '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
如果你选择正则表达式,重要提示(!):
当使用正则表达式(regexp
)时,必须设置全局标志("g");
否则,它将抛出一个类型错误(TypeError):"replaceAll必须使用全局RegExp调用"。
你也可以使用函数作为replaceWith
:
在这种情况下,在匹配完成后将调用该函数。
函数的结果(返回值)将用作替换字符串。