CodeQL documentation

String instead of regular expression

ID: js/string-instead-of-regex
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - correctness
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

Calling the builtin methods String.prototype.split and String.prototype.replace with a string as the first argument makes the methods search for that exact string. Providing a regular expression instead of the string makes the methods perform a regular expression search.

Calling the methods with a string that has the format of a regular expression is likely a mistake because the methods will not convert the string to a regular expression.

Recommendation

Call String.prototype.split and String.prototype.replace with a regular expression as the first argument unless you want an exact search.

Example

The following code snippet shows a call to String.prototype.replace. The purpose of the call is to remove all characters that are not alphanumeric.

			var cleaned = input.replace("[^a-zA-Z0-9]+", "");
		

Unfortunately, the first argument is a string and not a regular expression, so the call will only remove the first substring that is exactly “[^a-zA-Z0-9]+”.

Instead, the first argument should be a regular expression with the global flag set:

			var cleaned = input.replace(/[^a-zA-Z0-9]+/g, "");
		

References

  • © GitHub, Inc.
  • Terms
  • Privacy