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:

JavaScript
1/[aeiou]/

Explanation:
Matches any one vowel from the given set.


Basic Character Classes with Square Brackets

Square brackets define a group of allowed characters.

JavaScript
1let text = "cat";
2console.log(/[abc]/.test(text));

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.

JavaScript
1let text = "Version 7";
2console.log(/[0-9]/.test(text));

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.

JavaScript
1let text = "123abc";
2console.log(/[^0-9]/.test(text));

Explanation:
[^0-9] matches any non-digit character.


Predefined Character Classes

JavaScript provides built-in shortcuts for common character sets.

ClassMeaning
\dAny digit (0–9)
\DAny non-digit
\wWord character (letters, digits, underscore)
\WNon-word character
\sWhitespace (space, tab, newline)
\SNon-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

JavaScript
1let value = "Hello";
2console.log(/^[A-Za-z]+$/.test(value));

Explanation:
Ensures the string contains only letters.


Check if String Contains a Digit

JavaScript
1let value = "Code7";
2console.log(/\d/.test(value));

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

PatternMeaning
[abc]Any one of a, b, or c
[a-z]Any lowercase letter
[0-9]Any digit
[^a-z]Any character except lowercase letters
\dDigit
\wWord character
\sWhitespace

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.