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.
| 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" |
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:
Positive lookbehind (?<=...) and negative lookbehind (?<!...) were formalized in ES2018 and are supported across all modern browsers and Node.js environments.
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Core Web Vitals & JavaScript Impact | Named Capture Groups & Modern Regex Flags |
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.