pull/719/head
Zef Hemel 2024-02-23 13:47:27 +01:00
parent 60a42048ba
commit c307f09b7e
2 changed files with 17 additions and 6 deletions

View File

@ -7,13 +7,22 @@ export const builtinFunctions: FunctionMap = {
}, },
replace( replace(
str: string, str: string,
match: [string, string] | string, ...replacementPairs: any[]
replace: string,
) { ) {
const matcher = Array.isArray(match) if (replacementPairs.length % 2 !== 0) {
? new RegExp(match[0], match[1] + "g") throw new Error(
: match; "replace() requires an even number of replacement arguments",
return str.replaceAll(matcher, replace); );
}
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) => { json: (v: any) => {
return JSON.stringify(v); return JSON.stringify(v);

View File

@ -44,6 +44,8 @@ Current time.
## replace(str, match, replacement) ## 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”. 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) ## json(obj)
Convert the argument to a JSON string (for debugging purposes). Convert the argument to a JSON string (for debugging purposes).