diff --git a/lib/builtin_query_functions.ts b/lib/builtin_query_functions.ts index 3d0f82ee..e5a458fe 100644 --- a/lib/builtin_query_functions.ts +++ b/lib/builtin_query_functions.ts @@ -7,13 +7,22 @@ export const builtinFunctions: FunctionMap = { }, replace( str: string, - match: [string, string] | string, - replace: string, + ...replacementPairs: any[] ) { - const matcher = Array.isArray(match) - ? new RegExp(match[0], match[1] + "g") - : match; - return str.replaceAll(matcher, replace); + if (replacementPairs.length % 2 !== 0) { + throw new Error( + "replace() requires an even number of replacement arguments", + ); + } + for (let i = 0; i < replacementPairs.length; i += 2) { + const match = replacementPairs[i]; + const replace = replacementPairs[i + 1]; + const matcher = Array.isArray(match) + ? new RegExp(match[0], match[1] + "g") + : match; + str = str.replaceAll(matcher, replace); + } + return str; }, json: (v: any) => { return JSON.stringify(v); diff --git a/website/Functions.md b/website/Functions.md index 3efe0e87..c21c2d10 100644 --- a/website/Functions.md +++ b/website/Functions.md @@ -44,6 +44,8 @@ Current time. ## replace(str, match, replacement) Replace text in a string. `match` can either be a literal string or a regular expression: `replace("hello", "ell", "all")` would produce “hallo”, and `replace("hello", /l/, "b")` would produce “hebbo”. +This function supports an infinite number of replacements, so you can keep adding more, e.g. `replace(str, match1, replacement1, match2, replacement2, match3, replacement3)` + ## json(obj) Convert the argument to a JSON string (for debugging purposes).