Character escapes should be used properly when constructing a regular expression from string literal
- BAD_ESCAPE_AT_REGEXP_CONSTRUCTOR
- Error
- Medium
- No tags
This rule applies when character escapes are not properly used when constructing a regular expression from string literal.
A regular expression can be constructed from a string literal using the RegExp() constructor. In the string literal used, normal character escape rules are applied just like any other string. This can be confusing because a regular expression has different sets of escaping rules.
For example, new RegExp('\\s') should be used to maintain the backslash in the constructed regular expression. If new RegExp('\s') is used instead, s will be matched instead of a whitespace character. Note that under the string escape rule, \s is interpreted just as s.
This rule also applies to String.prototype.match() and String.prototype.search() that also construct regular expressions from string arguments.
Noncompliant Code Example
View with compliant examples side by sidefunction foo(x) {
return new RegExp('\$' + x); // BAD_ESCAPE_AT_REGEXP_CONSTRUCTOR alarm because '\$' is not properly escaped.
}Compliant Code Example
View with noncompliant examples side by sidefunction foo(x) {
return new RegExp('\\$' + x);
}Version
This rule was introduced in DeepScan 1.31.0.