The test() method of a global regular expression should be used with caution

  • BAD_TEST_WITH_GLOBAL_REGEXP
  • Error
  • Medium
  • No tags

This rule applies when the test() method of a regular expression with the global flag (g) is not used properly.

When the g flag is set, the matched index of the last invocation is recorded on the lastIndex property of the regular expression instance. Subsequent invocations begin the search at the index. So, if you call test() multiple times on the same instance, an incorrect false value can be returned.

To fix this problem, you should manually reset lastIndex to 0 before calling test().

Noncompliant Code Example

View with compliant examples side by side
let invalidCharRE = /[^a-zA-Z0-9_]/g;

export function isValid(str) {
    return !invalidCharRE.test(str); // BAD_TEST_WITH_GLOBAL_REGEXP alarm because the search may begin in the middle of 'str'.
}

export function makeValid(str) {
    return str.replace(invalidCharRE, "_");
}

Compliant Code Example

View with noncompliant examples side by side
let invalidCharRE = /[^a-zA-Z0-9_]/g;

export function isValid(str) {
    invalidCharRE.lastIndex = 0;
    return !invalidCharRE.test(str);
}

export function makeValid(str) {
    // This is ok because 'String.prototype.replace()' internally resets the 'lastIndex' property.
    return str.replace(invalidCharRE, "_");
}

Version

This rule was introduced in DeepScan 1.34.0.

See

Was this documentation helpful?