Character classes and ranges in regex
character class syntax, ranges, negated classes, shorthand classes \d \w \s, combining shorthands
Character Classes Match One of Many
Square brackets define a character class — a set of characters where exactly one must match at that position. [aeiou] matches any single lowercase vowel. [0-9] matches any digit via a range shorthand.
/[aeiou]/.test('sky') // false — no vowels
/[aeiou]/.test('the') // true — 'e' matches
/[a-z]/.test('A') // false — lowercase only
/[a-zA-Z]/.test('A') // true — upper and lower combined
Negated Classes
A caret ^ at the start of a class negates it: match any character NOT in the set.
/[^0-9]/.test('abc') // true — no digits
/[^0-9]/.test('a1b') // true — has non-digit chars
/[^a-z]+/.test('123') // true
Shorthand Classes
Three shorthands cover the most common sets:
\d—[0-9]\w—[a-zA-Z0-9_]\s— whitespace (space, tab, newline)
Their uppercase inverses negate them: \D matches any non-digit, \W any non-word character, \S any non-whitespace.
/\d{3}/.test('abc') // false
/\d{3}/.test('123') // true
/\w+/.test('hello_world') // true
Character classes compose well with quantifiers. [a-z]+ matches one or more lowercase letters; [0-9]{4} matches exactly four digits. You can also mix ranges and individual characters in one class: [a-z0-9_] matches any lowercase letter, digit, or underscore (which is equivalent to \w minus uppercase). When building patterns for identifiers, slugs, or usernames, combining ranges in a single class is cleaner and faster than alternation with multiple sub-patterns.
