Skip to content

Instantly share code, notes, and snippets.

@zzzarius
Created December 4, 2024 20:51
Show Gist options
  • Save zzzarius/afa6ce9586ef24196b128b25552f8ffc to your computer and use it in GitHub Desktop.
Save zzzarius/afa6ce9586ef24196b128b25552f8ffc to your computer and use it in GitHub Desktop.
Interpolate string template js
const interpolate = function(template, params) {
const names = Object.keys(params);
const vals = Object.values(params);
return new Function(...names, `return \`${template}\`;`)(...vals);
}
@zzzarius
Copy link
Author

zzzarius commented May 5, 2025

interpolate(
  "Welcome to the ${location}! ${Location} is a weird place to be right now.", 
  { location: "moon", Location: "Moon" }
);

> "Welcome to the moon! Moon is a weird place to be right now."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment