RegExp classes in JavaScript, also called character classes, are used to match one character from a group of allowed characters. They make patterns more flexible and powerful when validating input, searching text, or extracting specific characters from strings.
What Are RegExp Classes?
A RegExp class defines a set of characters that can match a single position in a string. Character classes are written inside square brackets [ ].
Example pattern:
Explanation:
Matches any one vowel from the given set.
Basic Character Classes with Square Brackets
Square brackets define a group of allowed characters.
Explanation:
The pattern matches if any one of a, b, or c exists in the string.
Ranges in Character Classes
Ranges allow matching characters between two values.
Explanation:
[0-9] matches any digit from 0 to 9.
Ranges also work for letters like [a-z] and [A-Z].
Negated Character Classes
A negated class matches any character except the ones listed.
Explanation:
[^0-9] matches any non-digit character.
Predefined Character Classes
JavaScript provides built-in shortcuts for common character sets.
| Class | Meaning |
|---|---|
\d | Any digit (0–9) |
\D | Any non-digit |
\w | Word character (letters, digits, underscore) |
\W | Non-word character |
\s | Whitespace (space, tab, newline) |
\S | Non-whitespace |
Combining Character Classes
Different character types can be combined in a single class.
Explanation:
Matches uppercase letters, digits, or the hyphen character.
Common Use Cases of RegExp Classes
Validate Alphabet-Only Input
Explanation:
Ensures the string contains only letters.
Check if String Contains a Digit
Explanation:
Checks whether at least one digit is present.
Common Mistakes with RegExp Classes
-
Using parentheses
()instead of square brackets[] -
Forgetting
^inside[]for negation -
Assuming
[a-z]matches uppercase letters -
Misplacing
-in ranges
Summary of RegExp Character Classes
| Pattern | Meaning |
|---|---|
[abc] | Any one of a, b, or c |
[a-z] | Any lowercase letter |
[0-9] | Any digit |
[^a-z] | Any character except lowercase letters |
\d | Digit |
\w | Word character |
\s | Whitespace |
Conclusion
RegExp classes in JavaScript provide a simple way to match specific groups of characters in text. By using square brackets, ranges, negation, and predefined classes like \d and \w, text validation and pattern matching become more precise and easier to manage in JavaScript applications.