Negated Character Classes
You'll learn how to match any character except the ones you specify using the caret (^) inside square brackets.
The Opposite of Character Classes
You already know that [abc] matches any single character that is a, b, or c. But what if you want to match anything except those letters? That's where negated character classes come in.
By placing a caret (^) immediately after the opening bracket, you flip the meaning: [^abc] matches any single character that is not a, b, or c.
How It Works
const pattern1 = /[^aeiou]/;
console.log(pattern1.test("b")); // true (b is not a vowel)
console.log(pattern1.test("e")); // false (e is a vowel)
const pattern2 = /[^0-9]/;
console.log(pattern2.test("5")); // false (5 is a digit)
console.log(pattern2.test("x")); // true (x is not a digit)
Think of negated character classes as an exclusion list: "Match anything except these characters."
Common Use Cases
const notDigit = /[^0-9]/g;
const text = "Room 101";
console.log(text.match(notDigit)); // ["R", "o", "o", "m", " "]
const notWhitespace = /[^ \t\n]/g;
const spaced = "a b c";
console.log(spaced.match(notWhitespace)); // ["a", "b", "c"]
The negated class matches one character at a time, just like a normal character class. It doesn't mean "match everything except this pattern"—it means "match one character that isn't in this set."
Key Takeaway: Use [^...] to match any single character that is not in the specified set—perfect for filtering out unwanted characters or matching "everything else."