Lookahead & Lookbehind Assertions
Lookahead & Lookbehind Assertions in Modern JavaScript
Regular expressions are central to input validation and string manipulation. Advanced pattern matching often requires verifying what precedes or follows a pattern without actually including those characters in the matched result. These zero-width assertions are known as Lookahead and Lookbehind assertions.
1. The 4 Lookaround Assertions
| Type | Syntax | Meaning | Example Match |
|---|---|---|---|
| Positive Lookahead | X(?=Y) | Match X only if followed immediately by Y | /\d+(?=px)/ matches 400 in "400px" |
| Negative Lookahead | X(?!Y) | Match X only if NOT followed by Y | /\d+(?!px)/ matches 400 in "400kg" |
| Positive Lookbehind | (?<=Y)X | Match X only if preceded immediately by Y | /(?<=\$)\d+/ matches 50 in "$50" |
| Negative Lookbehind | (?<!Y)X | Match X only if NOT preceded by Y | /(?<!\$)\d+/ matches 50 in "€50" |
2. Practical Examples
1. Extracting Monetary Amounts without Currency Symbols
2. Matching File Names by Extension
3. The Power of Multiple Lookaheads: Password Validation
In password validation, requiring at least one lowercase letter, one uppercase letter, one digit, and a minimum length is cumbersome with standard regex. Chained Lookaheads validate all conditions simultaneously from the start of the string:
4. Lookbehind Browser Compatibility (ES2018)
Positive lookbehind (?<=...) and negative lookbehind (?<!...) were formalized in ES2018 and are supported across all modern browsers and Node.js environments.
Practice Quiz
Named Capture Groups & Modern Regex Flags
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Core Web Vitals & JavaScript Impact | Named Capture Groups & Modern Regex Flags |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.