Even within "regular expressions" as a single idea, the escaping rules aren't universal — JavaScript's regex engine, PCRE (used by PHP and many other tools), and POSIX regex all disagree on which characters need a backslash. Curly braces are literal in POSIX basic regex but a quantifier delimiter in JavaScript and PCRE; the character class shorthand \d works in JS and PCRE but not in POSIX. Code that copies a regex pattern from one language to another without checking the target flavor is a common source of "it worked in my testing tool but not in production."
Escaping in a JavaScript/JSON string
In JS string literals and in JSON, special characters are escaped with a backslash: \" for a quote, \n for a newline, \\ for the backslash itself. JSON additionally requires all strings to use double quotes — unlike JS, where single quotes are also allowed.
Escaping in shell commands
On the command line, special characters include spaces, quotes, the dollar sign, asterisks, and others — they carry special meaning to the shell. A space inside a command argument needs to be escaped or the whole argument wrapped in quotes, otherwise the shell splits it into two separate arguments.
Escaping in regular expressions
In regular expressions, characters like the dot, asterisk, or parentheses carry special meaning (any character, a quantifier, a group). To match them literally rather than as metacharacters, a backslash goes in front: \. matches a literal dot, not "any character." Which exact set of characters counts as "special" depends on the regex flavor in use.
Why each context needs its own escaping
"Double escaping" or "under-escaping" mistakes are among the most common causes of broken code when inserting user text (say, a file path containing a space) into a command or a string. Correct escaping depends on where exactly the text is being inserted, not on the text itself.
Why you need this
- Preparing user text for safe insertion into a JSON request.
- Building a shell command with a dynamic argument without risking command injection.
- Escaping special characters before using text as a literal pattern in a regular expression.
Double escaping in nested contexts
When text passes through two contexts in sequence — for example, a string is embedded in JSON, and that JSON is then passed as a shell command argument — escaping must be applied in the right order: first for the inner context (JSON), then for the outer one (shell). Getting the order wrong or skipping a level is a common reason a "properly escaped" string still breaks in practice.