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

Matching Words Not Followed by Something

Using negative lookahead to find words or patterns that aren't followed by specific characters or words.

Matching Words Not Followed by Something

You'll learn how to use negative lookahead to find words or patterns only when they're not followed by specific text.

The Core Idea

Sometimes you want to match a word — but only when it doesn't have certain characters or words coming after it. This is where negative lookahead shines. You place (?!...) immediately after a pattern to say "match this, but only if what comes next is not what's inside the lookahead."

Think of it like a checkpoint: you're looking for a word, but before accepting it, you peek ahead to make sure something unwanted isn't there. If the coast is clear, you capture the word.

How It Works

The pattern \bword(?!pattern) breaks down as:

  • \bword — match the word (with a word boundary)
  • (?!pattern) — but only if "pattern" does not immediately follow

The lookahead doesn't consume characters; it just checks and moves on.

Example

const text = "I like cats and catfish, but not cat food.";
const regex = /cat(?!fish)/g;

console.log(text.match(regex)); 
// ["cat", "cat"] — matches "cat" in "cats" and "cat " but NOT "catfish"

Here, cat(?!fish) finds "cat" only when it's not followed by "fish". The word "cats" passes (followed by "s"), "cat " passes (followed by space), but "catfish" is rejected.

Real-World Use

This is invaluable for filtering: finding function names that aren't followed by parentheses, URLs that don't end in .pdf, or words that aren't part of a compound term.

Key Takeaway: Use (?!...) after a pattern to match it only when the specified text does NOT follow — perfect for excluding unwanted contexts without consuming characters.