-
-
Save 5pecia1/fc1a36d486cc2531c421e99b80009cd8 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: 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