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

Negated Shorthand Classes

Use \D, \W, and \S to match the inverse of digit, word, and whitespace classes.

Negated Shorthand Classes

What you'll learn: How to use the inverse versions of shorthand character classes to match everything except digits, word characters, or whitespace.


The Flip Side of Shortcuts

You've already learned about \d, \w, and \s — the handy shortcuts for matching digits, word characters, and whitespace. Now meet their opposites: negated shorthand classes use uppercase letters to match the inverse of what their lowercase versions match.

Think of them as "not" versions:

  • \D matches anything that is not a digit (everything except 0-9)
  • \W matches anything that is not a word character (everything except letters, digits, and underscores)
  • \S matches anything that is not whitespace (everything except spaces, tabs, newlines, etc.)

When to Use Them

These are perfect when you want to find "everything else." For example:

  • \D finds punctuation, letters, spaces — anything but numbers
  • \W finds spaces, punctuation, symbols — anything but alphanumeric characters and underscores
  • \S finds visible characters — anything but whitespace

They're particularly useful for validation patterns like "ensure there are no non-digit characters in this string" or "find the first non-whitespace character."

The Mental Model

Remember: lowercase = match these characters, uppercase = match everything else. The uppercase version is like flipping a switch from "allow" to "deny."

Key Takeaway: Use \D, \W, and \S to match the inverse of \d, \w, and \s — they're the "not" versions of the shorthand classes you already know.