Unix Environment Variable Reference in JS
Match Unix shell environment variable references in both $VAR and ${VAR} forms.
Try it in the JS tester →Pattern
regexJS
\$\{?([A-Z_][A-Z0-9_]*)\}? (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("\\$\\{?([A-Z_][A-Z0-9_]*)\\}?", "g");
const input = "Path is $HOME/.config";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
\$ matches the literal dollar sign. \{? optionally matches an opening brace. ([A-Z_][A-Z0-9_]*) captures the variable name: must start with a letter or underscore, followed by letters, digits, or underscores. \}? optionally matches the closing brace.
Examples
Input
Path is $HOME/.configMatches
$HOME
Input
export ${DATABASE_URL}Matches
${DATABASE_URL}
Input
no variables hereNo match
—