跳至主要内容

replace 函数

replace 在给定字符串中搜索另一个给定的子字符串,并将每个出现的子字符串替换为给定的替换字符串。

代码块
replace(string, substring, replacement)

如果 substring 用正斜杠括起来,则将其视为正则表达式,使用与 regex 相同的模式语法。如果对子字符串参数使用正则表达式,则 replacement 字符串可以通过使用 $n 序列合并输入中捕获的字符串,其中 n 是捕获组的索引或名称。

示例

代码块
> replace("1 + 2 + 3", "+", "-")
1 - 2 - 3

> replace("hello world", "/w.*d/", "everybody")
hello everybody
  • regex 在给定字符串中搜索与给定正则表达式模式匹配的子字符串。