CodeBlanks Logo Icon CodeBlanks

Character classes

JavaScript course · Intermediate · Lesson 119/134

Learn to narrow patterns with character classes like \d, \w and \s.

Character classes

A character class matches a whole set of characters with a single token. Built-in classes: \d digit, \w letter-digit-underscore, \s whitespace. You can also write your own with square brackets: [aeiou] matches one vowel.

/[aeiou]/.test("hello"); // true

Classes narrow your pattern and make the search precise. For example you can check that a field holds only digits with \d.

Negated classes

Every character class has an uppercase negated partner: \D matches a non-digit, \W a non-word character, \S a non-whitespace character.

"a5!".replace(/\D/g, ""); // "5"

This lets you do "remove everything that is not a digit" in one pattern. Negated classes are handy for targeting the characters you do not want.

Exercise Check whether a digit is present

Assign a regex literal that matches a digit to hasDigit. Then test it on the string "abc5def" with .test() and log the result with console.log.

Show example solution
/\d/.
Example solution:
let hasDigit = /\d/;
console.log(hasDigit.test("abc5def"));

Test yourself

  1. Which pattern matches a digit?

    • /\w/
    • /\s/
    • /\d/
    • /d/
    Show answer

    /\d/ — Correct! /\d/ matches a digit from 0 to 9.

  2. Match a whitespace character

    const space = ____;
    console.log(space.test("a b"));
    Show answer
    const space = /\s/;
    console.log(space.test("a b"));
  3. Match classes with their meaning

    \d
    digit
    \w
    letter/digit/_
    \s
    whitespace
    \D
    non-digit

All lessons in Intermediate