freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #34 of 61

regex · lookahead · lookbehind

LambdaVSThe Mutator
Lambda saysLookahead and lookbehind assert what comes next/before without consuming it.

Lookahead (?=…) / negative (?!…) match only if a pattern does/doesn't follow. Lookbehind (?<=…) / (?<!…) check what precedes. They're zero-width — they assert without including the text in the match. Classic use: insert thousands separators, or match a price after a currency symbol.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleMatch a number only when it follows a $ sign using lookbehind.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const m='price $42 and 99 apples'.match(/(?<=\$)\d+/);
document.getElementById('o').textContent='matched: '+m[0];</script></body></html>
▶ Open the interactive comic issue
‹ Regex · Groups · Capture · BackreferenceJson · Parse · Stringify · Replacer · Reviver ›