Skip to content

replace

替换一个或多个字符串或正则表达式。

语法

knap
{{ value | replace:"old":"new" }}
{{ value | replace:("a":"b", "c":"d") }}

用法

  • 每个带引号的查找取值后面跟一个冒号及其替换内容。
  • 正则表达式可以带标志,例如 "/[aeiou]/g"
  • 多个替换按从左到右的顺序应用。
  • 使用空替换内容即可删除匹配到的文本。
  • 支持的正则表达式标志为 gimsuy。若要按字面匹配冒号或管道等模板标点,请用反斜杠转义。

示例

移除文本

Data
json
{
  "message": "hello, world!"
}
Template
knap
{{ message | replace:",":"" }}
Output
md
hello world!

多重替换

Data
json
{
  "message": "hello world"
}
Template
knap
{{ message | replace:"e":"a","o":"0" }}
Output
md
hall0 w0rld

正则表达式

Data
json
{
  "message": "hello world"
}
Template
knap
{{ message | replace:"/[aeiou]/g":"*" }}
Output
md
h*ll* w*rld

不区分大小写的匹配

Data
json
{
  "message": "HELLO world"
}
Template
knap
{{ message | replace:"/hello/i":"hi" }}
Output
md
hi world