diff --git a/docs/templatefuncs.md b/docs/templatefuncs.md index 0a41b79..4d9a362 100644 --- a/docs/templatefuncs.md +++ b/docs/templatefuncs.md @@ -142,6 +142,16 @@ with *replacement* in *string*. far ``` +## `replaceAll` *old* *new* *string* + +`replaceAll` replaces all instances of *old* with *new* in *string*. + +```text +{{ "abcba" | replaceAll "b" "d" }} + +adcda +``` + ## `stat` *path* `stat` returns a map representation of executing diff --git a/templatefuncs.go b/templatefuncs.go index 812fb1e..de03047 100644 --- a/templatefuncs.go +++ b/templatefuncs.go @@ -43,6 +43,7 @@ func NewFuncMap() template.FuncMap { "prefixLines": prefixLinesTemplateFunc, "quote": eachString(strconv.Quote), "regexpReplaceAll": regexpReplaceAllTemplateFunc, + "replaceAll": replaceAllTemplateFunc, "stat": eachString(statTemplateFunc), "toJSON": toJSONTemplateFunc, "toLower": eachString(strings.ToLower), @@ -145,6 +146,13 @@ func prefixLinesTemplateFunc(prefix, s string) string { return builder.String() } +// replaceAllTemplateFunc is the `replaceAll` template function. +func replaceAllTemplateFunc(old, new string, v any) any { //nolint:predeclared + return eachString(func(s string) any { + return strings.ReplaceAll(s, old, new) + })(v) +} + // regexpReplaceAllTemplateFunc is the core implementation of the // `regexpReplaceAll` template function. func regexpReplaceAllTemplateFunc(expr, repl, s string) string { diff --git a/templatefuncs_test.go b/templatefuncs_test.go index 72029dd..5a13fa6 100644 --- a/templatefuncs_test.go +++ b/templatefuncs_test.go @@ -118,6 +118,14 @@ func TestFuncMap(t *testing.T) { "# b", ), }, + { + template: `{{ "abcba" | replaceAll "b" "d" }}`, + expected: `adcda`, + }, + { + template: `{{ list "abc" "cba" | replaceAll "b" "d" }}`, + expected: "[adc cda]", + }, { template: `{{ quote "a" }}`, expected: `"a"`,