Skip to content

Instantly share code, notes, and snippets.

@tohagan
Created January 18, 2020 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tohagan/108454abdf0f5f168ed6b54cf56aa158 to your computer and use it in GitHub Desktop.
Save tohagan/108454abdf0f5f168ed6b54cf56aa158 to your computer and use it in GitHub Desktop.
JavaScript - Expand variables in string
// Polyfill to expand variables in a string
// Example: "Welcome back ${name}. Glad to see you".expandVars({name: "Fred"});
// Variables defined in `vars` can be string/number values or a getter function.
// eslint-disable-next-line no-extend-native
String.prototype.expandVars = function(vars) {
return this.replace(/\${([^{}]*)}/g, function(str, varName) {
var value = vars[varName];
return typeof value === "string" || typeof value === "number" ? value : str;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment