Character Classes in JavaScript Regular Expressions (Live Playground)
Character classes in JavaScript regular expressions help you match specific types of characters in a string. In this tutorial, we'll discuss predefined character classes and how to create custom character classes.
Predefined Character Classes
JavaScript offers several predefined character classes to simplify pattern matching:
\d: Matches a digit (0-9).\w: Matches a word character (letters, digits, or underscores).\s: Matches whitespace characters (spaces, tabs, or line breaks).\D: Matches any non-digit character.\W: Matches any non-word character.\S: Matches any non-whitespace character.
Here are some examples:
const digits = /\d+/; // matches one or more digits
const words = /\w+/; // matches one or more word characters
Custom Character Classes
You can create custom character classes by placing a set of characters inside square brackets [...]. A custom character class matches any single character from the set.
Example:
const vowels = /[aeiou]/i; // matches any single vowel, case-insensitive
const punctuation = /[.,!?]/; // matches any single punctuation character
To specify a range of characters, use a hyphen - between the start and end characters:
const lowercaseLetters = /[a-z]/; // matches any single lowercase letter
const uppercaseLetters = /[A-Z]/; // matches any single uppercase letter
const allLetters = /[a-zA-Z]/; // matches any single letter, either lowercase or uppercase
Negating Character Classes
You can negate a custom character class by adding a caret ^ immediately after the opening square bracket. A negated character class matches any character that is not in the set.
Example:
const consonants = /[^aeiou]/i; // matches any single consonant, case-insensitive
const nonDigits = /[^0-9]/; // matches any character that is not a digit
Conclusion
In this tutorial, we discussed character classes in JavaScript regular expressions, which allow you to match specific types of characters. We covered predefined character classes, such as \d, \w, and \s, as well as custom character classes created using square brackets. Character classes are a powerful tool for writing concise and versatile regular expressions to match various patterns in strings.