Last active
February 10, 2024 18:01
-
-
Save DarrenSem/d153c4ced832e4d7ebe8d29af25f7968 to your computer and use it in GitHub Desktop.
replaced.js ( v, ...rules [ ArrayOf[ pattern, replaceWith, optionalRegExpFlags] ] ) -- flexible multiple string replacements (Flags default = "g")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// replaced.js ( v: any, ...rules: Array of [pattern: any, replaceWith: string | function, optionalRegExpFlags: string | null | undefined] ) | |
const replaced = (v, ...rules) => { | |
return rules.reduce( (acc, rule) => ( | |
acc.replace( | |
RegExp( rule[0], rule[2] == null ? "g" : rule[2] ), | |
rule[1] | |
) | |
), String( v ?? "" ) ); | |
}; | |
// Usage: console.log( replaced('hello happy world, hello world.', ['hello', 'hi'], ['world', 'planet', null], ['h', 'H', ""] ) === "Hi happy planet, hi planet." ); | |
// Usage: console.log( replaced(1.2300, [/\d/, "[$&]"]) === "[1].[2][3]" ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment