Negative Lookahead Syntax (?!...)
You'll learn how to assert that a specific pattern must not appear ahead of the current position in your regex match.
What Is Negative Lookahead?
While positive lookahead ((?=...)) checks that a pattern does appear ahead, negative lookahead ((?!...)) does the opposite—it succeeds only if the specified pattern does NOT match at that position. The key distinction: it looks ahead without consuming any characters, then moves on only if that pattern is absent.
Think of it like checking over a fence before walking forward. With negative lookahead, you peek ahead and only proceed if you don't see something specific. If you do see it, the match fails at that point.
Syntax and Usage
The syntax is (?!pattern) where pattern is what you want to avoid matching ahead.
// Match words that do NOT have a digit ahead
const regex = /\b\w+(?!\d)/g;
const text = "apple banana3 cherry4 date";
console.log(text.match(regex));
// ["apple", "banana", "cherry", "date"]
// Note: "banana" and "cherry" match the \w+ part, but fail (?!\d)
// Password must contain letters but NOT be all lowercase
const hasUppercase = /^(?!^[a-z]+$)[a-zA-Z]+$/;
console.log(hasUppercase.test("hello")); // false (all lowercase)
console.log(hasUppercase.test("Hello")); // true
console.log(hasUppercase.test("HELLO")); // true
// Match "cat" only if NOT followed by "fish"
const regex = /cat(?!fish)/;
console.log(regex.test("catfish")); // false
console.log(regex.test("category")); // true
console.log(regex.test("cat")); // true
Key Takeaway: Negative lookahead (?!...) lets you assert that a pattern must NOT appear ahead, enabling you to exclude specific matches without consuming characters—perfect for validation rules or filtering unwanted patterns.