JavaScript RegExp Character Classes
Matching groups of characters efficiently
📚 What are Character Classes?
Character classes allow you to match any character from a specific set. Instead of writing multiple patterns, you can define a group of characters to match in a single expression.
// Match any vowel
let pattern = /[aeiou]/;
console.log(pattern.test("hello")); // true (matches 'e')
console.log(pattern.test("xyz")); // false (no vowels)
Output:
true
false
Types of Character Classes
[abc] - Character Set
Matches any single character in the set
let pattern = /[abc]/;
console.log(pattern.test("apple")); // true
[^abc] - Negated Set
Matches any character NOT in the set
let pattern = /[^abc]/;
console.log(pattern.test("def")); // true
[a-z] - Range
Matches any character in the range
let pattern = /[a-z]/;
console.log(pattern.test("Hello")); // true
\d \w \s - Shortcuts
Predefined character classes
let pattern = /\d/; // digits
console.log(pattern.test("abc123")); // true
🔹 Basic Character Sets [abc]
Square brackets define a character set - matches any single character inside:
// Match any vowel
let vowels = /[aeiou]/;
console.log(vowels.test("hello")); // true (matches 'e')
console.log(vowels.test("world")); // true (matches 'o')
console.log(vowels.test("xyz")); // false (no vowels)
// Match specific letters
let pattern = /[abc]/;
console.log(pattern.test("apple")); // true (matches 'a')
console.log(pattern.test("banana")); // true (matches 'b')
console.log(pattern.test("cherry")); // true (matches 'c')
console.log(pattern.test("date")); // false (no a, b, or c)
// Find all vowels in text
let text = "Hello World";
let allVowels = text.match(/[aeiou]/gi);
console.log(allVowels); // ["e", "o", "o"]
Output:
true
true
false
true
true
true
false
["e", "o", "o"]
🔹 Negated Character Sets [^abc]
The caret (^) inside brackets means "NOT" - matches any character except those listed:
// Match any character that is NOT a vowel
let notVowels = /[^aeiou]/;
console.log(notVowels.test("hello")); // true (matches 'h')
console.log(notVowels.test("aeiou")); // false (all are vowels)
// Match any character that is NOT a digit
let notDigits = /[^0-9]/;
console.log(notDigits.test("123")); // false (all are digits)
console.log(notDigits.test("abc")); // true (matches 'a')
// Remove all vowels from text
let text = "Hello World";
let consonantsOnly = text.replace(/[aeiou]/gi, "");
console.log(consonantsOnly); // "Hll Wrld"
// Keep only letters (remove numbers and symbols)
let mixedText = "Hello123World!";
let lettersOnly = mixedText.replace(/[^a-zA-Z]/g, "");
console.log(lettersOnly); // "HelloWorld"
Output:
true
false
false
true
"Hll Wrld"
"HelloWorld"
🔹 Character Ranges [a-z]
Use hyphens to specify ranges of characters:
// Match any lowercase letter
let lowercase = /[a-z]/;
console.log(lowercase.test("Hello")); // true (matches 'e', 'l', 'l', 'o')
console.log(lowercase.test("HELLO")); // false (no lowercase)
// Match any uppercase letter
let uppercase = /[A-Z]/;
console.log(uppercase.test("Hello")); // true (matches 'H')
// Match any letter (upper or lower)
let anyLetter = /[a-zA-Z]/;
console.log(anyLetter.test("123")); // false
console.log(anyLetter.test("a1")); // true (matches 'a')
// Match any digit
let digit = /[0-9]/;
console.log(digit.test("abc")); // false
console.log(digit.test("a1b")); // true (matches '1')
// Combine ranges
let alphanumeric = /[a-zA-Z0-9]/;
console.log(alphanumeric.test("@#$")); // false
console.log(alphanumeric.test("a1@")); // true (matches 'a' or '1')
// Extract all letters and numbers
let text = "Hello123World!@#";
let alphanumericChars = text.match(/[a-zA-Z0-9]/g);
console.log(alphanumericChars); // ["H","e","l","l","o","1","2","3","W","o","r","l","d"]
Output:
true
false
true
false
true
false
true
false
true
["H","e","l","l","o","1","2","3","W","o","r","l","d"]
🔹 Predefined Character Classes
JavaScript provides shortcuts for common character classes:
📋 Common Shortcuts:
- \d - Digits [0-9]
- \D - Non-digits [^0-9]
- \w - Word characters [a-zA-Z0-9_]
- \W - Non-word characters [^a-zA-Z0-9_]
- \s - Whitespace [ \t\n\r\f]
- \S - Non-whitespace [^ \t\n\r\f]
// \d - Match digits
let digits = /\d/;
console.log(digits.test("abc123")); // true
console.log("Price: $25.99".match(/\d+/g)); // ["25", "99"]
// \w - Match word characters
let word = /\w/;
console.log(word.test("hello_123")); // true
console.log("[email protected]".match(/\w+/g)); // ["user", "email", "com"]
// \s - Match whitespace
let space = /\s/;
console.log(space.test("hello world")); // true
console.log("a b c".split(/\s+/)); // ["a", "b", "c"]
// Practical example: validate username
function isValidUsername(username) {
// Only letters, numbers, and underscores, 3-20 characters
let pattern = /^[a-zA-Z0-9_]{3,20}$/;
return pattern.test(username);
}
console.log(isValidUsername("user123")); // true
console.log(isValidUsername("user@name")); // false (contains @)
console.log(isValidUsername("ab")); // false (too short)
Output:
true
["25", "99"]
true
["user", "email", "com"]
true
["a", "b", "c"]
true
false
false
🔹 Practical Examples
Real-world applications of character classes:
🔸 Phone Number Validation
function formatPhoneNumber(phone) {
// Remove all non-digits
let cleaned = phone.replace(/[^\d]/g, '');
// Check if it's 10 digits
if (cleaned.length === 10) {
return cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
return "Invalid phone number";
}
console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
console.log(formatPhoneNumber("123-456-7890")); // "(123) 456-7890"
console.log(formatPhoneNumber("(123) 456-7890")); // "(123) 456-7890"
🔸 Password Strength Check
function checkPasswordStrength(password) {
let hasLower = /[a-z]/.test(password);
let hasUpper = /[A-Z]/.test(password);
let hasDigit = /[0-9]/.test(password);
let hasSpecial = /[^a-zA-Z0-9]/.test(password);
let isLongEnough = password.length >= 8;
let strength = 0;
if (hasLower) strength++;
if (hasUpper) strength++;
if (hasDigit) strength++;
if (hasSpecial) strength++;
if (isLongEnough) strength++;
return {
score: strength,
level: strength < 3 ? 'Weak' : strength < 5 ? 'Medium' : 'Strong'
};
}
console.log(checkPasswordStrength("password")); // {score: 2, level: "Weak"}
console.log(checkPasswordStrength("Password123!")); // {score: 5, level: "Strong"}
🔸 Extract Email Addresses
function extractEmails(text) {
// Simple email pattern using character classes
let emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
return text.match(emailPattern) || [];
}
let text = "Contact us at [email protected] or [email protected]";
console.log(extractEmails(text)); // ["[email protected]", "[email protected]"]