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
Fundamentals
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.
Concept
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.
Foundation
📝 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);
Cheat Sheet
⚡ Quick Reference
Goal
Code
Legacy recompile
regex.compile("new")
Change pattern + flags
regex.compile("pat", "gi")
Modern replacement
regex = new RegExp("pat", "gi")
Feature detect
typeof regex.compile === "function"
Read pattern after
regex.source, regex.flags
Standard today?
No — legacy only
Compare
📋 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
Hands-On
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')");
}
Check for compile before calling it. New code should skip the branch entirely and always use new RegExp().
Applications
🚀 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.
Important
📝 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.
Compatibility
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.
LimitedLegacy API
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · 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.
Wrap Up
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).
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about compile()
Legacy regex recompilation—and what to use instead.
5
Core concepts
📝01
Syntax
regex.compile(p,f)
API
🔄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.