How to Use Multiple replace or replaceRE Functions in Hugo


Suppose we want to apply multiple replace() or replaceRE() functions to our content in Hugo.

Let’s say we want to apply the following two functions.

{{ replace .Content "old1" "new1" | safeHTML }}
{{ replace .Content "old2" "new2" | safeHTML }}

First, we need to know where our content is being displayed.

We’ll do that by searching for usage of .Content.

Normally, we’ll find it in single.html.

{{ .Content }}

1. Nested replace() functions

We can simply nest the functions to apply both to our content.

{{- with .Content -}}
    {{ replace (replace . "old1" "new1") "old2" "new2" | safeHTML }}
{{- end -}}

2. Multiple replace() functions

If we have many replace() functions to apply, we can simply store them in temporary variables.

{{- with .Content -}}
    {{ $one := replace . "old1" "new1" }}
    {{ $two := replace $one "old2" "new2"}}
    {{ $final := replace $two "old3" "new3"}}
    {{ $final | safeHTML }}
{{- end -}}

We can, of course, use replaceRE() in all of these examples as well.