Advanced Pattern Matching & Replacement0%

Advanced Pattern Matching & Replacement

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

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:

JavaScript
// LEGACY WORKAROUND:
const str = "apple.orange.banana";
str.replace(/\./g, '/'); // Requires regex with /g!
 
// MODERN ES2021 STANDARD:
const clean = str.replaceAll('.', '/');
console.log(clean); // "apple/orange/banana"
Important Rule: If you pass a regular expression to 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:

JavaScript
// Syntax: (match, p1, p2, ..., offset, string, groups) => replacementString

Example: Dynamic Template Engine

JavaScript
const template = "Hello {{user.name}}, your account balance is {{account.balance}}.";
const context = {
user: { name: "Elena" },
account: { balance: "$450.00" }
};
 
function renderTemplate(tpl, data) {
return tpl.replace(/\{\{\s*([\w\.]+)\s*\}\}/g, (fullMatch, keyPath) => {
// Resolve nested object path (e.g. "user.name")
return keyPath.split('.').reduce((acc, part) => acc?.[part], data) ?? '';
});
}
 
console.log(renderTemplate(template, context));
// "Hello Elena, your account balance is $450.00."

3. Syntax Highlighting with Replacer Offsets

Replacer functions receive the offset (the index where the match was found in the source string):

JavaScript
function highlightKeywords(code) {
const keywords = /\b(const|let|var|function|return|class)\b/g;
 
return code.replace(keywords, (match, keyword, offset) => {
return `<span class="token-keyword" data-offset="${offset}">${keyword}</span>`;
});
}
 
const html = highlightKeywords('const x = 10; return x;');
console.log(html);
// <span class="token-keyword" data-offset="0">const</span> x = 10; <span class="token-keyword" data-offset="14">return</span> x;

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):

JavaScript
const tokenizerRegex = /\s*(\d+|\+|\*)\s*/y;
const codeInput = "42 + 10 * 5";
 
tokenizerRegex.lastIndex = 0;
const tokens = [];
 
while (tokenizerRegex.lastIndex < codeInput.length) {
const match = tokenizerRegex.exec(codeInput);
if (!match) throw new SyntaxError(`Unexpected token at ${tokenizerRegex.lastIndex}`);
tokens.push(match[1]);
}
 
console.log('Parsed Tokens:', tokens); // ['42', '+', '10', '*', '5']

Interactive Quiz

Practice Quiz

Question 1
What error occurs if you pass a non-global RegExp (without the g flag) to String.prototype.replaceAll()?
Question 2
What parameters does a replacer callback in String.prototype.replace() receive?
Question 3
How does the sticky flag (/y) differ from the global flag (/g)?
Question 4
Why are sticky regular expressions (/y) preferred when building parsers and compilers?
Question 5
In tpl.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] ?? ''), what does the key argument contain?
Next Lesson

History API & Client-Side Routing

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext