RegEx Metacharacter Escaper: Literal String Sanitization & Regex Safety
Escape reserved Regular Expression metacharacters with backslashes to safely pass dynamic user input into RegExp constructors without syntax exceptions.
The 14 Reserved ECMAScript RegEx Metacharacters
In JavaScript, Python, PHP, and PCRE regular expressions, exactly 14 characters possess special syntactic meaning:
\ ^ $ . * + ? ( ) [ ] { } |
- Attempting to pass unescaped user input (such as searching for price string
"$100.00 (USD)") intonew RegExp(userInput)causes fatal syntax errors or unintended matching behavior. - Escaping precedes every reserved character with a backslash:
\$100\.00 \(USD\), forcing the regex engine to treat each token as a literal string.
Preventing ReDoS (Regular Expression Denial of Service)
Passing unescaped raw user strings into server regular expressions exposes applications to catastrophic ReDoS vulnerabilities, where crafted input with catastrophic backtracking freezes server CPU threads at 100% utilization. Escaping metacharacters neutralizes injection attacks completely.
Pro Tip: Practical Application
In JavaScript code, always sanitize dynamic search strings with: string.replace(/[.*+?^$\{}()|[\]\\]/g, "\\amp;") before passing to RegExp.