In JavaScript, regular expressions are a powerful tool often used to match and search text. However, in actual development, we may need to use some special characters in regular expressions, such as backslash, regular expression metacharacters, spaces, etc. These characters have special meanings in regular expressions and need to be escaped to achieve the desired effect. Therefore, it is necessary for us to understand escaping in JavaScript regular expressions.
In JavaScript, backslash () is a special character, which we call an escape character. In regular expressions, escape characters can be used to shield special characters in regular expressions, causing them to lose their special meaning and become ordinary characters.
For example, for . in the regular expression, it can match any character. If we need to match an actual period (.), we need to escape it with a backslash:
let str = "my email is a.b@c.com"; let re = /a.b@c.com/; console.log(re.test(str)); // true
Regular expressions in JavaScript contain some special characters, which we call metacharacters. These metacharacters are matched according to their fixed meanings. For example, d matches any numeric character, w matches any alphabetic or numeric character, and s matches any whitespace character.
In regular expressions, if we want to match a specific metacharacter, we need to escape it. For example, if you need to match the actual character $, you need to add a backslash in front of it to escape it and turn it into $.
The following are some commonly used metacharacters and their escaped characters:
Metacharacters | Meaning | Escaped characters | ||
---|---|---|---|---|
Escape character | \ | |||
. | Matches any character except a newline character | . | ||
^ | Matches the beginning of the string | ^ | ||
$ | Matches the end of the string | $ | ||
* | Matches the preceding character zero or more times | * | ||
Matches the preceding character one or more times | ||||
? | Matches the preceding character zero or one time | ? | ||
{ n } | Matches the preceding character exactly n times | { n} | ||
{ n, } | Match The preceding character must be at least n times | { n,} | ||
Match the preceding character n to m times | { n,m} | |||
Matches any character in the square brackets | [ ] | |||
Group an expression into a subexpression | ( ) | |||
Represents or operates | ||||
Matches any numeric character | \d | |||
matches any whitespace character | \s | |||
Match any letter or numeric character | \w |