String.prototype.replaceAll() should not be called with a non-global regular expression

  • BAD_REPLACE_ALL_ARG
  • Error
  • High
  • es12

This rule applies when a regular expression without the global flag (g) is used at String.prototype.replaceAll().

Unlike other methods using regular expression, String.prototype.replaceAll() always replaces all matches in the input string. So, it is nonsensical to use a regular expression without the global flag at String.prototype.replaceAll(), which causes a TypeError exception.

Noncompliant Code Example

View with compliant examples side by side
const withSpaces = "foo bar   baz";
const withCommas = withSpaces.replaceAll(/\s+/, ','); // BAD_REPLACE_ALL_ARG alarm

Compliant Code Example

View with noncompliant examples side by side
const withSpaces = "foo bar   baz";
const withCommas = withSpaces.replaceAll(/\s+/g, ',');

Version

This rule was introduced in DeepScan 1.48.0.

See

Was this documentation helpful?