Skip to content

Instantly share code, notes, and snippets.

@signalwerk
Last active April 29, 2023 18:31
Show Gist options
  • Save signalwerk/39b5ee219ce9c3228d89712236fd4629 to your computer and use it in GitHub Desktop.
Save signalwerk/39b5ee219ce9c3228d89712236fd4629 to your computer and use it in GitHub Desktop.
Replace {{ values }} in String
// This is a basic templating function. It replaces any {{key}} in the
// string with the corresponding value in data. If no data is provided,
// then the template is returned as-is.
//
// Example:
// template("Hello, {{name}}!", { name: "John" }) → "Hello, John!"
// template("Hello, {{name}}!") → "Hello, {{name}}!"
export function template(string, data = {}) {
let out = string;
for (const [key, value] of Object.entries(data)) {
out = out.replace(`{{${key}}}`, value);
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment