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:
console.log("Chapter 7.1".match(/\d\.\d/)); // 7.1 (match!) console.log("Chapter 711".match(/\d\.\d/)); // null (searching for a real dot \.)
Parentheses also relate to the special characters. Hence, if you want them you can use \(. Let’s try to look for "g()" string:
console.log("function g()".match(/g\(\)/)); // "g()"
If you are searching for a backslash \, it is a special character in both regexps and strings. So, it should be doubled like this:
console.log("1\\2".match(/\\/)); // '\'
The search for a '/' is visualized in the example below:
console.log("/".match(/\//)); // '/'
In case you don’t use /.../ but create regexp using new RegExp, then it is not necessary to escape it:
console.log("/".match(new RegExp("/"))); // finds /
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:
let regexp = new RegExp("\d\.\d"); console.log("Chapter 3.2".match(regexp)); // null
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:
console.log("\d\.\d"); // d.d
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:
let regStr = "\\d\\.\\d"; console.log(regStr); // \d\.\d (correct now) let regexp = new RegExp(regStr); console.log("Chapter 3.2".match(regexp)); // 3.2