Skip to content

fix: handle escaped backslash before n/r in double-quoted values#1024

Open
JSap0914 wants to merge 1 commit into
motdotla:masterfrom
JSap0914:fix/escaped-backslash-expansion
Open

fix: handle escaped backslash before n/r in double-quoted values#1024
JSap0914 wants to merge 1 commit into
motdotla:masterfrom
JSap0914:fix/escaped-backslash-expansion

Conversation

@JSap0914

Copy link
Copy Markdown

Bug

In parse(), when a double-quoted value contains \\\\n or \\\\r (an escaped backslash followed by n or r), the two sequential replace() calls misfire. The second backslash plus the letter is consumed as a \\n/\\r escape sequence, leaving an orphaned first backslash and producing an unintended newline/carriage-return.

Example .env:

PATH_VALUE="path\\nvalue"

Before (buggy): path\ + newline + value
After (correct): path\nvalue (literal backslash-n)

Fix

Replace the two sequential replace() calls with a single-pass callback that scans escape sequences left-to-right:

  • \\n → newline
  • \\r → carriage return
  • \\\\ → single backslash (new)
  • anything else → kept as-is

This correctly handles \\\\n by first consuming \\\\ into a single backslash, then leaving the literal n untouched.

Verification

npm test
# { total: 202, pass: 202 }

Three new test cases added (ok 25–27 in test-parse.js). All 199 existing tests continue to pass.

AI-assisted contribution.

When a double-quoted .env value contains \\n or \\r (an escaped
backslash followed by n or r), the two sequential replace() calls
incorrectly expanded the sequence. For example KEY="path\\nvalue"
produced 'path\' + newline + 'value' instead of the expected literal
'path\nvalue'.

Replace the two sequential replacements with a single-pass callback
that processes each escape sequence left-to-right:
  \\n -> newline
  \\r -> carriage return
  \\\\ -> single backslash
  anything else -> kept as-is

This correctly handles KEY="path\\nvalue" -> 'path\nvalue' while
preserving the existing KEY="expand\nlines" -> 'expand' + LF + 'lines'
behaviour.
Copilot AI review requested due to automatic review settings June 17, 2026 13:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants