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

Predefined Character Classes

Master shorthand classes like \d (digits), \w (word chars), and \s (whitespace).

Predefined Character Classes

You'll learn the shorthand notation that makes matching common character types faster and more readable.

When writing regular expressions, you'll often need to match digits, letters, or spaces. Instead of spelling out [0-9] or [a-zA-Z0-9_] every time, JavaScript provides predefined character classes—compact shortcuts for the most common patterns.

The Big Three

\d – Digits

\d matches any digit from 0-9. It's identical to [0-9].

const hasNumber = /\d/.test("Room 404");
// true – matches '4'

\w – Word Characters

\w matches letters (a-z, A-Z), digits (0-9), and underscores (_). Think of it as [a-zA-Z0-9_]—anything that typically belongs in a "word" or identifier.

const validUsername = /^\w+$/.test("user_123");
// true – all word characters

\s – Whitespace

\s matches spaces, tabs, newlines, and other whitespace characters.

const hasSpace = /\s/.test("hello world");
// true – matches the space

Negated Versions

Each shorthand has an uppercase counterpart that means "NOT":

  • \D – anything except digits
  • \W – anything except word characters
  • \S – anything except whitespace
const noDigits = /^\D+$/.test("hello");
// true – no digits present

Why Use Them?

Compare /[0-9]+\.[0-9]+/ to /\d+\.\d+/ for matching decimals. Same result, less typing, easier to read at a glance. These shortcuts are like abbreviations in text messages—everyone knows what they mean, and they save time.

Key Takeaway: Use \d for digits, \w for word characters, \s for whitespace, and their uppercase versions (\D, \W, \S) to match the opposite.