Skip to content

Instantly share code, notes, and snippets.

@DarrenSem
Last active February 10, 2024 18:01
Show Gist options
  • Save DarrenSem/d153c4ced832e4d7ebe8d29af25f7968 to your computer and use it in GitHub Desktop.
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")
// 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