Curriculum
Module 23 // Core JavaScript
Regular Expressions (Essential)
Module Objective
test, match, replace, search, basic groups and flags
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Basic Search & Validation
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const testEmail = "subhajit@example.com";
console.log(emailPattern.test(testEmail)); // true
console.log(emailPattern.test("bad-email")); // false💡 The `.test()` method is the fastest way to check if a string matches a pattern. It returns a simple boolean.
// Example 2
// 2. Extracting Data (Groups)
const dateStr = "2025-12-17";
const pattern = /^(\d{4})-(\d{2})-(\d{2})$/;
const match = dateStr.match(pattern);
if (match) {
console.log("Year:", match[1]); // 2025
console.log("Month:", match[2]); // 12
console.log("Day:", match[3]); // 17
}💡 Parentheses `()` create **Capture Groups**. When using `.match()`, you can extract specific parts of the pattern from the result array.
// Example 3
// 3. Replace with Pattern
const text = "JS is fun. JS is fast.";
const clean = text.replace(/JS/g, "JavaScript");
console.log(clean); // "JavaScript is fun. JavaScript is fast."💡 The global flag `/g` ensures that all occurrences are replaced, not just the first one. Regular strings in `.replace()` only replace the first match.
Engine & Memory Architecture
Regex in Memory
1. Object Allocation:
- A Regex literal is created only once when the script is loaded.
- A Regex constructor creates a new object in the Heap every time it runs.
2. The State Machine:
- Internally, the engine compiles your Regex into a Deterministic Finite Automaton (DFA) or NFA.
- This state machine lives in the RAM and is used by the CPU to quickly walk through the target string.
3. Performance (ReDoS):
- Some patterns (like "greedy" quantifiers) can cause "catastrophic backtracking," making the CPU work exponentially harder.
- Safety: Always avoid nested quantifiers like
(a+)+which can freeze the browser.