Advanced Pattern Matching & Replacement
Advanced Pattern Matching & Replacement in Modern JavaScript
Beyond basic string search, modern JavaScript provides powerful pattern transformation tools. Mastering Replacer Functions, the modern replaceAll() API, and sticky matching enables complex text parsing, syntax highlighters, templating engines, and tokenizers.
1. String.prototype.replaceAll() (ES2021)
Historically, replacing all occurrences of a substring required global regular expressions:
replaceAll(), it must include the global g flag, otherwise it throws a TypeError: String.prototype.replaceAll called with a non-global RegExp.2. Advanced Replacer Callbacks in replace()
Instead of passing a static string replacement, pass a callback function that computes dynamic replacements per match:
Example: Dynamic Template Engine
3. Syntax Highlighting with Replacer Offsets
Replacer functions receive the offset (the index where the match was found in the source string):
4. The Sticky Flag (y) for High-Speed Tokenizers
The y (sticky) flag matches strictly starting at regex.lastIndex, without scanning forward in the string. This makes it ideal for building lexical tokenizers (compilers, Markdown parsers):
Practice Quiz
History API & Client-Side Routing
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Regex Denial of Service (ReDoS) Prevention | History API & Client-Side Routing |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.