RegExp.prototype.test() should not be used on always matching regular expressions

  • FUTILE_REGEXP_TEST
  • Error
  • Medium
  • No tags

This rule applies when the RegExp.prototype.test() result is always true because an always matching regular expression is used.

If a regular expression matches an empty string and is not anchored at both start and end, it matches an arbitrary input string as follows:

  • If the regular expression has an end anchor, the match succeeds with an empty substring at the end of the input when the preceding content is not matched.
  • Otherwise, the match succeeds with an empty substring at the start of the input when the remaining content is not matched.

In general, a regular expression matches an empty string in the following cases:

  1. The whole pattern consists of quantifiers allowing 0 repetition (e.g. /a*b?/).
  2. An empty alternative exists (e.g. /a||b/).

Noncompliant Code Example

View with compliant examples side by side
// Example 1
function isNumberSequence(str) {
    return /\d*(,\d*)*/.test(str); // FUTILE_REGEXP_TEST alarm because the whole pattern consists of quantifiers allowing 0 repetition.
}

// Example 2
function isFooOrBar(str) {
    return /foo||bar/.test(str); // FUTILE_REGEXP_TEST alarm because an empty alternative exists.
}

// Example 3
function isNumberOrNone(str) {
    return /^\d*|none$/.test(str); // FUTILE_REGEXP_TEST alarm because '^' and '$' have higher precedence than '|'.
}

Compliant Code Example

View with noncompliant examples side by side
// Example 1
function isNumberSequence(str) {
    return /\d+(,\d*)*/.test(str);
}

// Example 2
function isFooOrBar(str) {
    return /foo|bar/.test(str);
}

// Example 3
function isNumberOrNone(str) {
    return /^(\d*|none)$/.test(str);
}

Version

This rule was introduced in DeepScan 1.46.0.

See

Was this documentation helpful?