JavaScript RegExp Constructor

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is the RegExp Constructor?

new RegExp(pattern, flags?) creates a RegExp object from a pattern string and optional flags. Use it when the pattern is built at runtime; use a literal for fixed patterns.

Remember
new RegExp(pattern, flags?)

new RegExp("cat", "i")  →  /cat/i
new RegExp("\\d+")      →  /\d+/

literal (fixed):     /cat/i
constructor (dynamic): new RegExp(word, "gi")

regex.constructor === RegExp  →  true
UsePrefer
Fixed pattern/pattern/flags literal
Dynamic pattern / flagsnew RegExp(pattern, flags)
Type checkvalue instanceof RegExp

How to Use new RegExp()

Pass a pattern string, optional flags, then use test / exec.

  1. Build the pattern as a string (escape metacharacters if it comes from user input).
  2. Call new RegExp(pattern, flags) — flags like "g", "i", "m".
  3. Use the result with test(), exec(), or string methods like match.
  4. For a constant pattern, prefer a literal /pattern/flags instead.
PieceRequired?Role
patternYesPattern string (or another RegExp)
flagsOptionalFlag string, e.g. "gi"
Return value—New RegExp object

Pseudocode

Pseudocode
pattern = string pattern
flags = optional flags string

if pattern is invalid:
    throw SyntaxError

return new RegExp object with that pattern and flags
// same kind of object as /pattern/flags

Cheat Sheet

Keep these facts handy while creating regexes.

TopicDetail
Syntaxnew RegExp(pattern, flags?)
Common flagsg global, i ignore case, m multiline
vs literalConstructor for dynamic patterns; literal for fixed
BackslashesIn strings, write "\\d" to get \d
.constructorInstance property pointing at RegExp
Invalid patternThrows SyntaxError
StandardCore language — all environments

Live Preview

Build a RegExp with the constructor and test it against sample text.

Browser demo of new RegExp(pattern, flags) — same idea as the examples below.

Result
regex = new RegExp("cat", "i")
→ /cat/i

test("The Cat sat") → true

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Basic new RegExp

Create a case-insensitive regex and test a string.

JavaScript
const regex = new RegExp("cat", "i");

console.log(regex.toString());     // "/cat/i"
console.log(regex.test("The Cat")); // true
console.log(regex.constructor === RegExp); // true
Try It Yourself

How It Works

  1. Create the regex. Pattern "cat", flag "i" (ignore case).
  2. Inspect it. toString() shows /cat/i.
  3. Test text. "The Cat" matches because of the i flag.
  4. Constructor property. regex.constructor is the RegExp function.

Example 2 — Dynamic Pattern from a Variable

Build a regex when the word is not known until runtime.

JavaScript
const word = "fun";
const regex = new RegExp(word, "i");

console.log(regex.test("CodeToFun")); // true
console.log(regex.test("boring"));    // false
Try It Yourself

How It Works

  1. Store the word. word could come from input or config.
  2. Build the regex. new RegExp(word, "i") uses that string as the pattern.
  3. Match. "CodeToFun" contains "fun" → true.
  4. Miss. "boring" has no fun → false.

Example 3 — Literal vs Constructor

Same matching behavior; different ways to create the object.

JavaScript
const fromLiteral = /\d+/;
const fromCtor = new RegExp("\\d+");

console.log(fromLiteral.test("42")); // true
console.log(fromCtor.test("42"));    // true
console.log(fromLiteral instanceof RegExp); // true
console.log(fromCtor instanceof RegExp);    // true
Try It Yourself

How It Works

  1. Literal form. /\d+/ is a fixed digit pattern written in code.
  2. Constructor form. In a string you need "\\d+" so the regex engine sees \d+.
  3. Same tests. Both match "42".
  4. Same type. Both pass instanceof RegExp.

Edge Cases & Pitfalls

Check these before building regexes from strings.

trap

Double backslashes in strings

Write "\\d" in a string to get the pattern \d. A single "\d" is not a digit class.

syntax

Invalid patterns throw

new RegExp("(") throws SyntaxError. Guard dynamic patterns with try/catch.

security

Escape user input

Unescaped metacharacters in user text can change meaning or break the pattern. Escape before interpolating.

typecheck

Prefer instanceof RegExp

constructor can be overwritten. instanceof is the usual type check for RegExp values.

Browser & Runtime Support

new RegExp(pattern, flags) is a core language feature — available in every JavaScript environment.

✓ Baseline · Widely available

RegExp constructor

Supported in all browsers and Node.js versions. Safe for every target with no polyfill.

100% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
new RegExp() Universal

Bottom line: Use freely. Prefer literals for fixed patterns and the constructor when the pattern or flags are dynamic.

Performance Notes

ApproachCostBest for
Literal /p/fCompile onceFixed patterns
new RegExp(p, f)Compile each callDynamic patterns
Reuse one RegExpCheapest in loopsRepeated matching

Creating a RegExp has a compile cost. Build it once outside a hot loop when the pattern does not change. Literals are fine and often clearer for constants.

Key Takeaways

  • Role: create a RegExp from a pattern string and optional flags.
  • When: use the constructor for dynamic patterns; literals for fixed ones.
  • Strings: remember "\\d" in code to get the pattern \d.
  • Type check: prefer instanceof RegExp over trusting .constructor.

One line: new RegExp(pattern, flags) builds regexes from strings — use it when the pattern is dynamic; use literals when it is fixed.

Frequently Asked Questions

new RegExp(pattern, flags) creates a RegExp object from a pattern string and optional flags. Use it when the pattern or flags are built at runtime.
Use a literal (/pattern/flags) for fixed patterns. Use new RegExp when the pattern or flags come from variables, user input, or string concatenation.
Yes for clarity: new RegExp(pattern, flags). Calling RegExp(pattern, flags) without new also creates a RegExp, but new is the usual style.
Every RegExp instance has a constructor property that points to the RegExp function. Prefer instanceof RegExp for type checks; use new RegExp(...) to create regexes.
Escape regex metacharacters in user text before building the pattern — for example replace special chars with a backslash-escaped form — or you may get a SyntaxError or unintended matches.
new RegExp throws a SyntaxError if the pattern string is not valid. Wrap creation in try/catch when the pattern is untrusted or built dynamically.

Next: compile()

See the deprecated legacy way to recompile a RegExp in place — and why new RegExp is better.

compile() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful