JavaScript RegExp compile() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Legacy · deprecated

What You’ll Learn

compile() is a legacy RegExp method that swaps the pattern (and optional flags) on an existing regex object. You will rarely need it today—but understanding it helps when reading old scripts and choosing the modern new RegExp() replacement.

01

Syntax

regex.compile(p, f)

02

Mutates

Same object

03

Returns

That RegExp

04

Legacy

Not in spec

05

Modern

new RegExp()

06

Detect

typeof check

Introduction

A regular expression in JavaScript is usually created with a literal like /pattern/flags or the RegExp constructor. Once built, the pattern normally stays fixed unless you create a new object.

In very old JavaScript (Netscape 4 era), compile() let developers keep one RegExp variable and recompile it when the search pattern changed—for example, when a user picked a different filter. Modern code simply assigns regex = new RegExp(nextPattern, flags) instead.

Understanding the compile() Method

RegExp.prototype.compile(pattern, flags?) updates the internal pattern of an existing RegExp instance:

  • In-place mutation — the object identity stays the same; only source and flags change.
  • Return value — returns the same RegExp (handy for chaining in legacy style).
  • lastIndex reset — in engines that support it, lastIndex goes back to 0 after recompilation.
  • Non-standard — not part of ECMAScript; availability varies. Treat it as historical, not portable.
⚠️
Important for beginners

Do not use compile() in new projects. Learn it so you recognize legacy code, then reach for new RegExp(pattern, flags) every time.

📝 Syntax

JavaScript
regex.compile(pattern[, flags])

Parameters

  • regex — an existing RegExp object (the method mutates it).
  • pattern — string pattern for the new regex (same rules as the RegExp constructor).
  • flags (optional) — flag string such as "i", "g", or "gi".

Return value

  • The same RegExp object, now holding the updated pattern and flags.

Modern equivalent

JavaScript
regex = new RegExp(pattern, flags);

⚡ Quick Reference

GoalCode
Legacy recompileregex.compile("new")
Change pattern + flagsregex.compile("pat", "gi")
Modern replacementregex = new RegExp("pat", "gi")
Feature detecttypeof regex.compile === "function"
Read pattern afterregex.source, regex.flags
Standard today?No — legacy only

📋 compile() vs new RegExp()

Both can change what a regex matches—but only one belongs in modern code.

compile()
mutates object

Legacy in-place

new RegExp()
new instance

Standard approach

Literal /pat/
fixed pattern

When static

Portability
new RegExp wins

Works everywhere

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples that call compile() guard with a typeof check so they fail gracefully when the method is missing.

📚 Getting Started

See how compile() swaps a pattern on one object.

Example 1 — Recompile with a New Pattern

Start with /cat/, call compile("dog"), then test a string.

JavaScript
const regex = /cat/;

if (typeof regex.compile === "function") {
  regex.compile("dog");
  console.log(regex.source);       // "dog"
  console.log(regex.test("I have a dog"));  // true
} else {
  console.log("Use: regex = new RegExp('dog')");
}
Try It Yourself

How It Works

compile() replaces the internal pattern while keeping the same object reference. After the call, regex.source reads "dog" instead of "cat".

📈 Practical Patterns

Flags, modern replacements, and runtime switching.

Example 2 — Update Pattern and Flags

Pass a second argument to set case-insensitive matching.

JavaScript
const regex = /hello/;

if (typeof regex.compile === "function") {
  regex.compile("HELLO", "i");
  console.log(regex.source, regex.flags);  // HELLO i
  console.log(regex.test("say HELLO there"));  // true
}
Try It Yourself

How It Works

The second argument replaces the entire flag set—just like the RegExp constructor. The i flag makes matching ignore letter case.

Example 3 — Modern Alternative with new RegExp()

Prefer reassignment when you need a different pattern.

JavaScript
let regex = /old-pattern/;

regex = new RegExp("new-pattern", "i");

console.log(regex.source);                  // "new-pattern"
console.log(regex.test("NEW-PATTERN works"));  // true
Try It Yourself

How It Works

Reassigning regex is clearer and portable. Any code holding the old reference still sees the old pattern—which is usually safer than silent mutation.

Example 4 — Dynamic Pattern Switcher

Pick a named pattern at runtime—the use case compile() was built for, done the modern way.

JavaScript
const patterns = {
  email: "[^@\\s]+@[^@\\s]+\\.\\w+",
  digits: "\\d+"
};

let regex = /placeholder/;
const text = "Order 42 shipped";

function usePattern(name) {
  regex = new RegExp(patterns[name]);
}

usePattern("digits");
console.log(regex.exec(text)[0]);  // "42"
Try It Yourself

How It Works

Store pattern strings in a lookup object, then build a RegExp when the user chooses a filter. No compile() required.

Example 5 — Feature Detection and Fallback

Safe pattern for maintaining very old code paths.

JavaScript
let regex = /start/;

function setPattern(pattern, flags) {
  if (typeof regex.compile === "function") {
    regex.compile(pattern, flags);
  } else {
    regex = new RegExp(pattern, flags);
  }
  return regex;
}

setPattern("end");
console.log(regex.source);  // "end"
Try It Yourself

How It Works

Check for compile before calling it. New code should skip the branch entirely and always use new RegExp().

🚀 Common Use Cases (Historical)

  • Legacy search widgets — old pages reused one RegExp when users changed search terms.
  • Reading archived scripts — recognize compile() when maintaining Netscape-era code.
  • Shared object references — mutation updated every alias; modern code avoids that surprise.
  • Dynamic validation — today, build new RegExp from user-selected rule names.
  • Gradual migration — feature-detect compile(), fall back to constructor during refactors.
  • Teaching regex basics — compare mutable legacy APIs with immutable-style modern patterns.

🧠 What Happens When You Call compile()

1

Parse new pattern

The engine compiles the string pattern (and optional flags) internally.

Pattern string
2

Mutate the object

source and flags update on the same RegExp instance.

In-place
3

Reset search state

lastIndex typically returns to 0 so the next exec starts fresh.

Global regex
4

Return same RegExp

Call test(), exec(), or match() with the updated pattern.

📝 Notes

  • compile() is deprecated and not in the ECMAScript specification.
  • Chrome, Firefox, and Node (V8) may still expose it; do not assume it in strict portable code.
  • Prefer regex = new RegExp(pattern, flags) for all new development.
  • Mutation can surprise other modules holding the same RegExp reference.
  • Invalid patterns throw SyntaxError, same as the RegExp constructor.
  • For user-supplied search text, escape metacharacters before building a pattern.

Browser & Runtime Support

compile() is a legacy non-standard method. It may exist in V8-based runtimes but is absent from the ECMAScript spec and should not be used in portable code.

Legacy · non-standard

RegExp compile()

Present as a compatibility hook in some engines (Chrome, Node). Not guaranteed everywhere. Use new RegExp() instead for production code.

Limited Legacy API
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
RegExp compile() Avoid in new code

Bottom line: Treat compile() as historical documentation. Standard RegExp constructor and literals work in every modern environment.

Conclusion

RegExp.prototype.compile() recompiled patterns on an existing object in legacy JavaScript. You might encounter it in old tutorials or archived code, but modern projects should create fresh RegExp instances with new RegExp(pattern, flags).

Next, learn the RegExp constructor property or return to the regular expressions overview.

💡 Best Practices

✅ Do

  • Use new RegExp(pattern, flags) for dynamic patterns
  • Feature-detect before calling legacy compile()
  • Escape user input when building regex strings
  • Read regex.source and regex.flags to debug
  • Prefer regex literals when the pattern is fixed

❌ Don’t

  • Introduce compile() in new codebases
  • Assume compile exists in all runtimes
  • Mutate shared RegExp objects unexpectedly
  • Confuse compile with RegExp constructor compilation
  • Skip validation on user-built patterns

Key Takeaways

Knowledge Unlocked

Five things to remember about compile()

Legacy regex recompilation—and what to use instead.

5
Core concepts
🔄 02

Mutates

Same object.

Behavior
⚠️ 03

Legacy

Not in spec.

Status
04

Modern

new RegExp.

Replace
🔍 05

Detect

typeof check.

Safe

❓ Frequently Asked Questions

It recompiles an existing RegExp object with a new pattern and optional flags. The same object is mutated in place and returned—useful in legacy code that kept one RegExp reference and swapped patterns.
No. compile() is a legacy Netscape-era method. It was never included in the ECMAScript standard (removed before ES3). Some engines like V8 still ship it for backward compatibility, but you should not rely on it in new code.
Assign a fresh RegExp: regex = new RegExp(pattern, flags). That works everywhere, reads clearly, and avoids mutating a shared object unexpectedly.
No. It returns the same RegExp instance after updating its internal pattern and flags. Any variable still pointing at that object sees the change.
In engines that support compile(), lastIndex is typically reset to 0 because the pattern changed. With global or sticky regexes, that avoids stale search positions.
Use typeof regex.compile === 'function' before calling it, then fall back to new RegExp(pattern, flags) when it is missing.
Did you know?

When engines support compile(), it returns the same RegExp object—so regex.compile("a") === regex is true. With new RegExp("a"), you always get a fresh object.

Continue to RegExp constructor

Learn how the constructor property identifies RegExp objects.

constructor 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.

6 people found this page helpful