In Regular Expressions, Character Classes (often called shorthand character classes) are special backslash \ notations used to match specific types of characters, like digits, letters, or whitespace.
They provide a fast and clean way to search for generic types of data without typing out every single letter or number.
| Class | Description | Matches |
|---|---|---|
\d |
Digit | Any number from 0 to 9. |
\D |
Non-Digit | Any character that is not a number. |
\w |
Word Character | Any alphanumeric character (a-z, A-Z, 0-9) and the underscore (_). |
\W |
Non-Word Char | Any character that is not a word character (e.g., spaces, punctuation). |
\s |
Whitespace | Any space, tab, or newline character. |
\S |
Non-Whitespace | Any character that is not a space, tab, or newline. |
Pro Tip: Notice the pattern? A lowercase letter matches the type (e.g.,
\dfor digit), and the uppercase version does the exact opposite (\Dfor non-digit)!
\dThe \d class is incredibly useful for finding phone numbers, zip codes, or extracting numeric values from messy strings.
let text = "My phone number is 555-1234.";// Find all digits in the string using \d and the 'g' flag let result = text.match(/\d/g);
console.log(result); // ["5", "5", "5", "1", "2", "3", "4"]
\wThe \w class matches "word characters". It is important to remember that \w includes numbers and underscores (_), but not spaces or punctuation.
let text = "Hello World! 100%";// Match all word characters let words = text.match(/\w/g); console.log(words.join("")); // HelloWorld100
// Match all NON-word characters let nonWords = text.match(/\W/g); console.log(nonWords); // [" ", "!", " ", "%"]
\sThe \s class is perfect for splitting strings into arrays based on spaces, or for cleaning up extra spaces inside a document.
let text = "Is this too much space?";// Let's replace every whitespace character with a hyphen let clean = text.replace(/\s/g, "-");
console.log(clean); // "Is-this----too-much---space?"
Which character class would you use to match ANY character that is NOT a number (0-9)?