JS RegExp Classes

JavaScript RegExp Character Classes

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.


Common Character Classes

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., \d for digit), and the uppercase version does the exact opposite (\D for non-digit)!


1. Extracting Digits with \d

The \d class is incredibly useful for finding phone numbers, zip codes, or extracting numeric values from messy strings.

\d Character Class

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"]


2. Word Characters with \w

The \w class matches "word characters". It is important to remember that \w includes numbers and underscores (_), but not spaces or punctuation.

\w vs \W Example

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); // [" ", "!", " ", "%"]


3. Handling Whitespace with \s

The \s class is perfect for splitting strings into arrays based on spaces, or for cleaning up extra spaces inside a document.

\s Character Class

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?"


Exercise

?

Which character class would you use to match ANY character that is NOT a number (0-9)?