JavaScript RegExp compile() Method

Beginner
5 min read
Updated: Oct 2026
3 examples
Deprecated

What Is compile()?

RegExp.prototype.compile(pattern, flags?) recompiles an existing RegExp in place with a new pattern and optional flags. It returns the same object after mutating it.

Remember
regex.compile(pattern, flags?)

mutates the same RegExp object
returns that same object
legacy / non-standard

prefer:
  regex = new RegExp(pattern, flags)
UsePrefer
Change pattern (legacy)regex.compile(p, f) — learn only
Change pattern (modern)regex = new RegExp(p, f)
Create once/pattern/flags or new RegExp

How to Use compile()

Study the legacy call, then replace it with new RegExp in real projects.

  1. Start with an existing RegExp object.
  2. Call regex.compile(pattern, flags) — flags are optional.
  3. The same object now has the new source / flags.
  4. For new code, assign regex = new RegExp(pattern, flags) instead.
PieceRequired?Role
RegExp objectYesReceiver to recompile
patternYesNew pattern string (or RegExp)
flagsOptionalNew flags string (e.g. "gi")

Pseudocode

Pseudocode
regex = existing RegExp

// legacy:
regex.compile(pattern, flags?)
// same object updated in place
// lastIndex usually reset to 0

// modern replace:
regex = new RegExp(pattern, flags)

Cheat Sheet

Keep these facts handy when reading legacy regex code.

TopicDetail
Syntaxregex.compile(pattern, flags?)
ReturnsSame RegExp object (mutated)
Mutates?Yes — in place
StatusDeprecated / non-standard
Modern replacenew RegExp(pattern, flags)
lastIndexTypically reset to 0

Live Preview

Recompile a RegExp (when available) and compare with new RegExp.

Browser demo — learn the legacy API; prefer new RegExp in real apps.

Result
regex = /abc/i
regex.compile("cat", "g")
→ /cat/g  (same object)

modern: new RegExp("cat", "g") → /cat/g

JavaScript Examples

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

Example 1 — Basic Recompile

Change the pattern and flags on an existing RegExp (legacy).

JavaScript
const regex = /cat/i;

if (typeof regex.compile === "function") {
  regex.compile("dog", "g");
  console.log(regex.source); // "dog"
  console.log(regex.flags);  // "g"
  console.log(regex.test("dog")); // true
} else {
  console.log("compile() not available");
}
Try It Yourself

How It Works

  1. Start with a regex. /cat/i is the initial pattern and flags.
  2. Feature-detect. Check typeof regex.compile === "function".
  3. Recompile. compile("dog", "g") replaces pattern and flags on the same object.
  4. Test. regex.test("dog") is now true.

Example 2 — Same Object Returned

compile() mutates and returns the original instance.

JavaScript
const regex = /abc/;
const ref = regex;

if (typeof regex.compile === "function") {
  const result = regex.compile("xyz");
  console.log(result === regex); // true
  console.log(ref.source);       // "xyz"
} else {
  console.log("compile() not available");
}
Try It Yourself

How It Works

  1. Alias the object. ref and regex point to the same RegExp.
  2. Call compile. Pattern becomes "xyz" on that object.
  3. Return value. result === regex is true — not a new instance.
  4. Shared refs update. ref.source is also "xyz".

Example 3 — Prefer new RegExp

Compare the legacy call with the modern, standard approach.

JavaScript
let regex = /cat/i;

// Legacy — do not use in new code
if (typeof regex.compile === "function") {
  regex.compile("dog", "g");
}

// Prefer — standard and clear
regex = new RegExp("dog", "g");

console.log(regex.source); // "dog"
console.log(regex.flags);  // "g"
console.log(regex.test("dog")); // true
Try It Yourself

How It Works

  1. Legacy path. compile() mutates the old object (if present).
  2. Modern path. new RegExp("dog", "g") creates a fresh standard RegExp.
  3. Reassign. regex = … points at the new object — clear ownership.
  4. Rule of thumb. Learn compile() to read old code; ship new RegExp.

Edge Cases & Pitfalls

Check these before you copy compile() from old tutorials.

deprecated

Not in the ECMAScript standard

Some engines still ship it for compatibility. Others may not. Always feature-detect or avoid it.

mutation

Shared references change together

Because the object is mutated, every alias of that RegExp sees the new pattern — easy to surprise callers.

lastIndex

lastIndex usually resets

After recompile, search position is typically 0. Do not assume a previous global search position remains.

replace

Prefer new RegExp

Creating a new RegExp is standard, clearer, and works in every modern environment.

Browser & Runtime Support

RegExp.prototype.compile() is legacy / non-standard. Some engines (e.g. V8 / Chrome / Node) still expose it; do not depend on it in new projects.

✓ Deprecated · Non-standard

RegExp.prototype.compile()

May exist for backward compatibility in Chromium-based environments. Not guaranteed everywhere. Prefer new RegExp(pattern, flags).

Legacy Compatibility only
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
compile() Avoid in new code

Bottom line: Recognize compile() in old code. For new apps, always use new RegExp(pattern, flags) or a regex literal — feature-detect if you must touch the legacy API.

Performance Notes

ApproachCostBest for
regex.compile(p, f)Recompile costLegacy recognition only
new RegExp(p, f)Create + compileModern pattern switching
Regex literal /p/fCompile onceFixed patterns

Cost is similar to creating a new RegExp. The real issue is portability and surprising mutation — not microseconds. Prefer new RegExp for clarity and standards compliance.

Key Takeaways

  • Role: recompile an existing RegExp in place with a new pattern/flags.
  • Status: deprecated / non-standard — learn it, do not ship it.
  • Replace: use new RegExp(pattern, flags).
  • Mutation: same object updates — shared refs all see the change.

One line: compile() is a legacy in-place recompiler — recognize it in old code, and use new RegExp for new code.

Frequently Asked Questions

compile(pattern, flags) recompiles an existing RegExp object with a new pattern and optional flags. It mutates the same object in place and returns it.
Yes. It is a legacy, non-standard method (Netscape-era). It is not part of the ECMAScript standard. Prefer new RegExp(pattern, flags) in new code.
No. It returns the same RegExp instance after updating its pattern and flags. Any variable still pointing at that object sees the change.
Assign a fresh RegExp: regex = new RegExp(pattern, flags). That works everywhere, reads clearly, and avoids mutating a shared object.
In engines that support compile(), lastIndex is typically reset to 0 because the pattern changed. That avoids stale search positions for global or sticky regexes.
Use typeof regex.compile === "function" before calling it, then fall back to new RegExp(pattern, flags) when it is missing.

Next: toString()

Learn how a RegExp becomes a readable /pattern/flags string.

toString() 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