The \
(backslash) character indicates that the next character should be treated as a literal character rather than as a special
character or string delimiter. For instance, it is common to escape single quotes inside a string literal using the single quote delimiter like
'It\'s a beautiful day'
. Escaping is only meaningful for special characters. Escaping non-special characters in strings, template
literals, and regular expressions doesn’t affect their value.
Therefore, useless escapes impact code readability and could even denote a bug in the code if the developer left it by mistake or intended to
escape another special character instead.
You should check if the escape character was not misplaced. Useless character escapes can safely be removed without changing the original
value.
Valid escape sequences are those escaping:
- control characters like
\n
(newline), \t
(tab), \r
(carriage return), etc.
- the backslash character itself:
\\
- the single and double quote characters:
\'
and \"
- the dollar sign
\$
character, used in a string interpolation
- unicode escape sequences like
\u{1F600}
or \u1F600
- hexadecimal escape sequences like
\x41
Noncompliant code example
const number = '\8';
const hello = 'Hello, world\!'; // Noncompliant: '!' is not a special character
const string1 = 'this string contains 2 \"double quotes\"'; // Noncompliant: you can use double quotes here
const string2 = "this string contains 2 \'single quotes\'"; // Noncompliant: you can use single quotes here
Compliant solution
const number = '8';
const hello = 'Hello, world!';
const string1 = 'this string contains 2 "double quotes"';
const string2 = "this string contains 2 'single quotes'";