As we’ve seen, a backslash \ is used to denote character classes, e.g. \d. So it’s a special character in regexps (just like in regular strings).
There are other special characters as well, that have special meaning in a regexp, such as [ ] { } ( ) \ ^ $ . | ? * +. They are used to do more powerful searches.
Don’t try to remember the list – soon we’ll deal with each of them, and you’ll know them by heart automatically.
Escaping
Let’s say we want to find literally a dot. 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".
For example:
Parentheses are also special characters, so if we want them, we should use \(. The example below looks for a string "g()":
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
A slash symbol '/' is not a special character, but in JavaScript it is used to open and close the regexp: /...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:
new RegExp
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:
The similar search in one of previous examples worked with /\d\.\d/, but new RegExp("\d\.\d") doesn’t work, why?
The reason is that backslashes are "consumed" by a string. As we may recall, regular strings have their own special characters, such as \n, and a backslash is used for escaping.
Here’s how "\d.\d" is perceived:
String quotes "consume" backslashes and interpret them on their own, for instance:
\n– becomes a newline character,\u1234– becomes the Unicode character with such code,- ...And when there’s no special meaning: like
\dor\z, then the backslash is simply removed.
So new RegExp gets a string without backslashes. That’s why the search doesn’t work!
To fix it, we need to double backslashes, because string quotes turn \\ into \:
Summary
- To search for special characters
[ \ ^ $ . | ? * + ( )literally, we need to prepend them with a backslash\("escape them"). - We also need to escape
/if we’re inside/.../(but not insidenew RegExp). - When passing a string to
new RegExp, we need to double backslashes\\, cause string quotes consume one of them.
Comments
<code>tag, for several lines – wrap them in<pre>tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen...)