.env File Key-Value Line in JS
Parse KEY=value lines from .env config files, handling quoted values and trailing comments.
Try it in the JS tester →Pattern
regexJS
^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$ (flags: m)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("^([A-Z_][A-Z0-9_]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^#\\s]*))(?:\\s*#.*)?$", "m");
const input = "DATABASE_URL=postgres://localhost/db";
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
([A-Z_][A-Z0-9_]*) captures the variable name (uppercase + underscores by convention). The value alternation supports double-quoted, single-quoted, and unquoted values. (?:\s*#.*)? allows an optional inline comment. The m flag lets ^ and $ match individual lines in a multi-line file.
Examples
Input
DATABASE_URL=postgres://localhost/dbMatches
DATABASE_URL=postgres://localhost/db
Input
API_KEY="sk_live_abc123" # productionMatches
API_KEY="sk_live_abc123" # production
Input
lowercase=badNo match
—