include::../description.adoc[]

== Noncompliant Code Example

Example with RegExp:

----
function (req, res) {
  const pattern = RegExp(req.query.pattern); // Noncompliant
  pattern.test(req.query.input);
};
----
Don't use https://www.npmjs.com/package/safe-regex[safe-regex] kind of libraries to validate regexes, as it is prone to FPs/FNs:

----
const safe = require('safe-regex');

function (req, res) {
  // Not a good validator, eg of FN: http://test/noncompliant?pattern=^(a|aa)%2B$&input=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!
  if(safe(req.query.pattern)) {
    const regex = RegExp(req.query.pattern); // Noncompliant
    regex.test(req.query.input);
  }
};
----

== Compliant Solution

Escape regex special characters:

----
const escapeStringRegexp = require('escape-string-regexp');

function (req, res) {
  const pattern = RegExp(escapeStringRegexp(req.query.pattern)); // Compliant
  pattern.test(req.query.input);
};
----

include::../see.adoc[]

ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
