If the string literal you have is "\\"
and you want to match the characters within that string value, you only need to match \
because the value of the string is \
.
If the string literal you have is "\\\\"
, you need to match \\
because the value of the string is \\
.
With a regular expression literal you'd have to escape the backslash just like you would within a string literal:
/\\/g //matches any single backslash character
/\\\\/g //matches any double backslash characters
With a regular expression string passed to the RegExp
constructor, you'd have to escape the backslash for the string, and then again for the regular expression:
new RegExp("\\\\", 'g'); //matches any single backslash character
new RegExp("\\\\\\\\", 'g'); //matches any double backslash characters
Strings passed to the regular expression constructor need to have a value identical to what you'd use in a regular expression literal. This means an extra level of escaping certain characters. This can become especially confusing with some characters that need to be escaped for the string, but not the regular expression value, and other characters that need to be escaped for the regular expression but not the string literal.
For example, a quote character ("
or '
) within a string needs to be escaped otherwise it'll end the string literal:
/"/ //regular expression to match a double quote
new RegExp("\""); //regular expression string to match a double quote character
new RegExp('"'); //alternative regular expression string to match a double quote character
Note how the backslash doesn't need to be double escaped.
As another example a .
character needs to be escaped within a regular expression otherwise it'll match any character that isn't a line terminator:
/\./ //regular expression to match a period character
new RegExp('\\.'); //regular expression string to match a period character
Note how the backslash character does need to be double escaped.