The special characters are usually encoded by using the exception of @*_+-./. They are used mainly for doing more powerful searches. The full list of the special characters looks as follows: [ \ ^ $ . | ? * + ( ).
Imagine that you want to search for a dot. To meet that goal you need to use a special character like a regular one, prepending it with a backslash \ (also known as “escaping a character”), like this:
Parentheses also relate to the special characters. Hence, if you want them you can use \(. Let’s try to look for "g()" string:
If you are searching for a backslash \, it is a special character in both regexps and strings. So, it should be doubled like this:
The search for a '/' is visualized in the example below:
In case you don’t use /.../ but create regexp using new RegExp, then it is not necessary to escape it:
The New Regexp
While creating a regular expression using new RegExp, then it is not necessary to escape / but some other escaping should be done.
Let’s consider the following example:
Such a search works with /\d\.\d/, but new RegExp("\d\.\d") is invalid. Let’s find out why.
The primary reason is that a string consumes backslashes. Regular strings contain own special characters such as \n. And backslash is applied for escaping.
The“\d.\d” is perceived in this way:
Backslashes are consumed by string quotes and interpreted on their own, as follows:
- \n transforms into a newline character.
- \u1234 transforms into the Unicode character.
- When there is not any special meaning such as \d or \z, the backslash should be removed.
The new RegExp receives a string without the backslash. For this reason, the search fails.
For fixing it, you should double backslashes as string quotes turn \\ into \, like here: