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.
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.Instead of passing a static string replacement, pass a callback function that computes dynamic replacements per match:
Replacer functions receive the offset (the index where the match was found in the source string):
y) for High-Speed TokenizersThe 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):
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Regex Denial of Service (ReDoS) Prevention | History API & Client-Side Routing |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.