Created
January 18, 2020 03:07
-
-
Save tohagan/108454abdf0f5f168ed6b54cf56aa158 to your computer and use it in GitHub Desktop.
JavaScript - Expand variables in string
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
// 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