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

Character Classes with Square Brackets

Learn to match any single character from a set using [abc] notation and understand range syntax.

Character Classes with Square Brackets

You'll learn how to match any single character from a specific set using square bracket notation in regular expressions.

What Are Character Classes?

Until now, you've matched exact characters or used the dot (.) to match any character. But what if you want to match "any vowel" or "any digit"? That's where character classes come in.

Square brackets [...] let you define a set of characters. The regex engine will match exactly one character from that set.

Basic Syntax

const vowelPattern = /[aeiou]/;
console.log(vowelPattern.test("apple"));  // true
console.log(vowelPattern.test("sky"));    // true (matches 'y'? No! Only a, e, i, o, u)
console.log(vowelPattern.test("xyz"));    // false

The pattern [aeiou] matches one character that is either a, e, i, o, or u.

Range Syntax

Instead of listing every character, you can use a hyphen to specify ranges:

const digitPattern = /[0-9]/;
console.log(digitPattern.test("Order 5"));  // true (matches '5')

const lowerPattern = /[a-z]/;
console.log(lowerPattern.test("Hello"));    // true (matches 'e', 'l', 'o')

const alphaNumPattern = /[a-zA-Z0-9]/;
console.log(alphaNumPattern.test("2Fast")); // true

[a-z] matches any lowercase letter. [A-Z] matches uppercase. You can combine ranges: [a-zA-Z0-9] matches any letter or digit.

Think of It Like a Menu

A character class is like a restaurant menu: you pick one item from the list. [abc] means "I'll accept an a, a b, or a c — just one."

Key Takeaway: Character classes [...] match a single character from a defined set, and ranges like [a-z] or [0-9] provide shorthand for consecutive characters.