Course contentsShow
← JavaScript
Lesson 1715 of 2,72336. Regular ExpressionsFree lesson

Negative Lookbehind Syntax (?<!...)

Using negative lookbehind to assert that a pattern must NOT appear behind the current position.

Negative Lookbehind Syntax (?<!...)

You'll learn how to ensure a pattern is not preceded by specific characters without consuming them.

The Opposite of Positive Lookbehind

While positive lookbehind (?<=...) checks that something must appear before your match, negative lookbehind (?<!...) does the reverse: it asserts that a pattern must NOT appear immediately behind the current position.

Think of it like a bouncer checking IDs backwards: "You can only enter if you're NOT coming from the restricted area." The assertion checks what's behind but doesn't consume any characters from the match itself.

How It Works

The syntax (?<!pattern) creates a zero-width assertion. The regex engine looks backward from the current position and fails the match if pattern is found there.

// Match "apple" only when NOT preceded by "red "
const regex = /(?<!red )apple/g;

console.log("I like apple pie".match(regex));        // ["apple"]
console.log("I like red apple pie".match(regex));    // null
console.log("The green apple is tasty".match(regex)); // ["apple"]

Practical Example

// Match prices NOT preceded by dollar signs
const text = "Item: €50, $30, 25, £40";
const noDollar = /(?<!\$)\d+/g;

console.log(text.match(noDollar)); // ["50", "25", "40"]
// The "30" is excluded because it follows "$"

Notice how negative lookbehind lets you be selective about context without including that context in your match. You're finding digits, but specifically avoiding those that come after a dollar sign.

Key Takeaway: Negative lookbehind (?<!...) ensures a pattern does NOT appear behind the current position—perfect for context-aware matching where you need to exclude specific preceding patterns.