diff --git a/docs/string.md b/docs/string.md index 62873e5..2642e1b 100644 --- a/docs/string.md +++ b/docs/string.md @@ -13,6 +13,7 @@ local string = import "github.com/jsonnet-libs/xtd/string.libsonnet" ## Index * [`fn splitEscape(str, c, escape='\\')`](#fn-splitescape) +* [`fn strReplaceMulti(str, replacements)`](#fn-strreplacemulti) ## Fields @@ -24,3 +25,18 @@ splitEscape(str, c, escape='\\') `split` works the same as `std.split` but with support for escaping the dividing string `c`. + + +### fn strReplaceMulti + +```ts +strReplaceMulti(str, replacements) +``` + +`strReplaceMulti` replaces multiple substrings in a string. + +Example: +```jsonnet +strReplaceMulti('hello world', [['hello', 'goodbye'], ['world', 'universe']]) +// 'goodbye universe' +``` diff --git a/string.libsonnet b/string.libsonnet index 6655981..5dccf13 100644 --- a/string.libsonnet +++ b/string.libsonnet @@ -32,4 +32,30 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet'; c, ) ), + + '#strReplaceMulti':: d.fn( + ||| + `strReplaceMulti` replaces multiple substrings in a string. + + Example: + ```jsonnet + strReplaceMulti('hello world', [['hello', 'goodbye'], ['world', 'universe']]) + // 'goodbye universe' + ``` + |||, + [ + d.arg('str', d.T.string), + d.arg('replacements', d.T.array), + ] + ), + strReplaceMulti(str, replacements): + assert std.isString(str) : 'str must be a string'; + assert std.isArray(replacements) : 'replacements must be an array'; + assert std.all([std.isArray(r) && std.length(r) == 2 && std.isString(r[0]) && std.isString(r[1]) for r in replacements]) : 'replacements must be an array of arrays of strings'; + std.foldl( + function(acc, replacement) + std.strReplace(acc, replacement[0], replacement[1]), + replacements, + str, + ), } diff --git a/test/string_test.jsonnet b/test/string_test.jsonnet new file mode 100644 index 0000000..4f375eb --- /dev/null +++ b/test/string_test.jsonnet @@ -0,0 +1,33 @@ +local string = import '../string.libsonnet'; +local test = import 'github.com/jsonnet-libs/testonnet/main.libsonnet'; + +test.new(std.thisFile) + ++ test.case.new( + name='strReplaceMulti', + test=test.expect.eq( + actual=string.strReplaceMulti('hello world', [['hello', 'goodbye'], ['world', 'universe']]), + expected='goodbye universe', + ) +) ++ test.case.new( + name='strReplaceMulti - chained', + test=test.expect.eq( + actual=string.strReplaceMulti('hello world', [['hello', 'goodbye'], ['goodbye', 'hi again']]), + expected='hi again world', + ) +) ++ test.case.new( + name='strReplaceMulti - not found', + test=test.expect.eq( + actual=string.strReplaceMulti('hello world', [['first', 'second'], ['third', 'fourth']]), + expected='hello world', + ) +) ++ test.case.new( + name='strReplaceMulti - empty replacements', + test=test.expect.eq( + actual=string.strReplaceMulti('hello world', []), + expected='hello world', + ) +)