Created
January 6, 2024 18:34
-
-
Save LukeChannings/f3d2595fd18ed9e0dffc538e553936cf to your computer and use it in GitHub Desktop.
Safe string interpolation function
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
/** | |
* 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