As we’ve seen, a backslash
"\" is used to denote character classes. So it’s a special character in regexps (just like in a regular string).
There are other special characters as well, that have special meaning in a regexp. They are used to do more powerful searches. Here’s a full list of them:
[ \ ^ $ . | ? * + ( ).
Don’t try to remember the list – soon we’ll deal with each of them separately and you’ll know them by heart automatically.
Let’s say we want to find a dot literally. Not “any character”, but just a dot.
To use a special character as a regular one, prepend it with a backslash:
That’s also called “escaping a character”.
Parentheses are also special characters, so if we want them, we should use
\(. The example below looks for a string
If we’re looking for a backslash
\, it’s a special character in both regular strings and regexps, so we should double it.
A slash symbol
/...pattern.../, so we should escape it too.
Here’s what a search for a slash
'/' looks like:
On the other hand, if we’re not using
/.../, but create a regexp using
new RegExp, then we don’t need to escape it:
If we are creating a regular expression with
new RegExp, then we don’t have to escape
/, but need to do some other escaping.
For instance, consider this:
It worked with
/\d\.\d/, but with
new RegExp("\d\.\d") it doesn’t, why?
The reason is that backslashes are “consumed” by a string. Remember, regular strings have their own special characters like
\n, and a backslash is used for escaping.
Please, take a look, what “\d.\d” really is:
The quotes “consume” backslashes and interpret them, for instance:
\n– becomes a newline character,
\u1234– becomes the Unicode character with such code,
- …And when there’s no special meaning: like
\z, then the backslash is simply removed.
So the call to
new RegExp gets a string without backslashes. That’s why it doesn’t work!
To fix it, we need to double backslashes, because quotes turn
- To search special characters
[ \ ^ $ . | ? * + ( )literally, we need to prepend them with
- We also need to escape
/if we’re inside
/.../(but not inside
- When passing a string
new RegExp, we need to double backslashes
\\, cause strings consume one of them.