Skip to content

Instantly share code, notes, and snippets.

@5pecia1
Forked from tohagan/expandVars.js
Last active August 13, 2021 04:58
Show Gist options
  • Save 5pecia1/fc1a36d486cc2531c421e99b80009cd8 to your computer and use it in GitHub Desktop.
Save 5pecia1/fc1a36d486cc2531c421e99b80009cd8 to your computer and use it in GitHub Desktop.
JavaScript - Expand variables in string
// Polyfill to expand variables in a string
// Example: expandEnv("Welcome back ${name}. Glad to see you");
// Example: expandEnv("Welcome back $name. Glad to see you");
// eslint-disable-next-line no-extend-native
function expandEnv(s: string): string {
return s.replace(/\$([\w]+|{([^{}]*)})/g, (str, varName) => {
const vName = varName.startsWith("{") ? varName.substring(1, varName.length - 1) : varName;
var value = process.env[vName];
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