liveBook · Manning

RegExp constructor

As explained in Secrets of the JavaScript Ninja, Third Edition

The RegExp constructor is the JavaScript built-in constructor that creates regular expression objects from a pattern and optional flags.

The RegExp constructor creates a regular-expression object from a string pattern. For a fixed pattern such as `test`, `new RegExp("test")` produces the same kind of instance as the literal `/test/`; flags can be supplied as a second argument. section 12.2.1 section 12.7

Prefer a literal for fixed patterns: backslashes in constructor strings must also be escaped for the string syntax, which can make patterns harder to read. The constructor is useful when a pattern must be assembled at runtime. Treat arbitrary user-supplied regexes cautiously, since they can saturate CPU; use `RegExp.escape(string)` when inserting user text as a literal match. section 12.2.1

const fileExtension = isTypeScript ? "ts" : "js"; 
const pattern = new RegExp(`\\.${fileExtension}$`);  

A runtime choice of file extension becomes part of the constructed pattern. section 12.2.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains literal equivalence, flags, escaping, and runtime risks without detailing constructor internals.
Examples
Contrasts `/test/` with `new RegExp("test")` and constructs a matcher from a runtime-selected file extension.
What you can do after
Build it from scratch by constructing a regex from a runtime-selected file extension.
How it connects
Connects regular-expression literals, flags, string escaping, and RegExp.escape.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.