Parse a .env file
A free hard coding practice problem from devops. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.
- Difficulty
- Hard
- Type
- Function
- Topic
- Devops
- Languages
- JavaScript, TypeScript or Python
Problem
Parse the contents of a .env file. Split text on \n into lines and, for each line, trim spaces and tabs from both ends, then:
1. skip it if it is empty or starts with #;
2. if it starts with export (the word and one space), remove that prefix and trim again;
3. skip it if it has no =; otherwise the KEY is the text before the first = (trimmed) and the raw value is the text after it (trimmed);
4. skip it unless the key matches [A-Za-z_][A-Za-z0-9_]*;
5. if the raw value is at least 2 characters long and starts AND ends with ", the value is the text between them with every two-character sequence \n (backslash, n) turned into a newline character; if it starts and ends with ', the value is the text between them unchanged;
6. otherwise, if the raw value contains # (space then hash), cut it at the first occurrence; trim the result — that is the value.
Return [[key, value], …] in the order each key FIRST appears; when a key appears again, its value is replaced by the later one. text is printable ASCII plus newlines and tabs, at most 10 000 characters.
Function signature
// JavaScript
function parseDotenv(text)
// TypeScript
function parseDotenv(text: any): any
// Python
def parse_dotenv(text):Examples
parseDotenv("# config\nPORT=8080\nexport NAME = \"Metatron app\"\nDEBUG=true # local only\nPORT=9090")→[["PORT","9090"],["NAME","Metatron app"],["DEBUG","true"]]parseDotenv("A='x # y'\nB=\"line1\\nline2\"\n1BAD=no\nnoequals")→[["A","x # y"],["B","line1\nline2"]]
How checking works
Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.