Skip to content

Instantly share code, notes, and snippets.

@LukeChannings
Created January 6, 2024 18:34
Show Gist options
  • Save LukeChannings/f3d2595fd18ed9e0dffc538e553936cf to your computer and use it in GitHub Desktop.
Save LukeChannings/f3d2595fd18ed9e0dffc538e553936cf to your computer and use it in GitHub Desktop.
Safe string interpolation function
/**
* interpolate
* @description replaces substrings within a string template with values in a context dictionary
* @example interpolate("hello ${name}", { name: "Jerry" })
* @param {string} template a template string
* @param {Record<string, string>} context
* @returns {string}
*/
const interpolate = (template, context) =>
template.replaceAll(/\${([a-z_$][a-z0-9_$]+?)}/gi, (raw, name) =>
typeof context[name] === "string" ? context[name] : raw,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment