We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 67 - Lookahead & Lookbehind Assertions in Regular Expressions

Lookahead and lookbehind assertions in regular expressions allow you to match a pattern based on what comes before or after it, without including those parts in the match. They are useful for complex pattern matching.

Lookahead Assertions

A lookahead assertion checks if a certain pattern appears after the current position without consuming it.

Positive Lookahead (?=...)

It matches a group only if it is followed by a certain pattern.

Example:

let text = "apple123 banana456 cherry789";
let regex = /\d+(?= banana)/g;
console.log(text.match(regex)); // ["123"]

Explanation: It finds numbers before "banana".

Negative Lookahead (?!...)

It ensures a pattern is not followed by a certain string.

Example:

let text = "apple123 banana456 cherry789";
let regex = /\d+(?! banana)/g;
console.log(text.match(regex)); // ["456", "789"]

Explanation: It matches numbers not followed by "banana".

Lookbehind Assertions

A lookbehind assertion checks if a certain pattern appears before the current position without consuming it.

Positive Lookbehind (?<=...)

It matches a group only if it is preceded by a certain pattern.

Example:

let text = "apple123 banana456 cherry789";
let regex = /(?<=banana)\d+/g;
console.log(text.match(regex)); // ["456"]

Explanation: It finds numbers after "banana".

Negative Lookbehind (?<!...)

It ensures a pattern is not preceded by a certain string.

Example:

let text = "apple123 banana456 cherry789";
let regex = /(?<!banana)\d+/g;
console.log(text.match(regex)); // ["123", "789"]

Explanation: It matches numbers not preceded by "banana".

Summary

Assertion Type Syntax Matches
Positive Lookahead X(?=Y) X if followed by Y
Negative Lookahead X(?!Y) X if NOT followed by Y
Positive Lookbehind (?<=X)Y Y if preceded by X
Negative Lookbehind (?<!X)Y Y if NOT preceded by X

Try It Yourself

Experiment with different lookaheads and lookbehinds on regex101.com.