Useless Backslash Escape
ID |
javascript.no_useless_escape |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-style, suspicious-comparison |
Description
Reports backslash escapes inside "…" and '…' string literals where the escaped character has no special meaning. JavaScript silently drops the backslash at runtime — "\d" evaluates to "d" — which usually means the developer mistook the literal for a regex pattern or copied a regex source into the wrong literal kind.
Rationale
-
"\d","\p{L}","\\!"are common typos when porting regex source into a string literal. -
The literal works "by accident" because the misspelled escape collapses to its trailing character, so unit tests pass and the bug ships.
-
The code reads as if it had special meaning when it does not, which misleads reviewers.
// Bad - silently equivalent to "d+", "(", "!"
const numbers = "\d+";
const opener = "\(";
const banged = "\!";
Remediation
Either drop the unnecessary backslash, or — if the intent was a regex — use a proper regex literal.
// Good
const numbers = /\d+/;
const opener = "(";
const banged = "!";