CodeQL documentation

String instead of regular expression

ID: js/string-instead-of-regex
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - 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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy