Clean β’ Professional
In JavaScript, regular expressions (RegEx) allow you to match patterns in strings. Character classes are a fundamental concept that define a set of characters you want to match. They are enclosed in square brackets [] or use predefined shorthand notations for common patterns.
Character classes let you match any one character from a specified set or range.
| Syntax | Description | Example |
|---|---|---|
[abc] | Matches any one character in the set (a, b, or c) | "cat".match(/[abc]/g) β ["c","a"] |
[a-z] | Matches any lowercase letter | "hello".match(/[a-z]/g) β ["h","e","l","l","o"] |
[A-Z] | Matches any uppercase letter | "HELLO".match(/[A-Z]/g) β ["H","E","L","L","O"] |
[0-9] | Matches any digit | "123".match(/[0-9]/g) β ["1","2","3"] |
[a-zA-Z0-9] | Matches any alphanumeric character | "Ab1".match(/[a-zA-Z0-9]/g) β ["A","b","1"] |
Use ^ inside brackets to negate the set. It matches any character not listed.
const regex = /[^0-9]/; // Matches any non-digit
console.log(regex.test("a")); // true
console.log(regex.test("5")); // false
JavaScript provides shortcuts for commonly used character sets:
| Syntax | Matches | Example |
|---|---|---|
\\d | Any digit [0-9] | /\\d/.test('5') β true |
\\D | Any non-digit [^0-9] | /\\D/.test('a') β true |
\\w | Any word character [a-zA-Z0-9_] | /\\w/.test('G') β true |
\\W | Any non-word character | /\\W/.test('@') β true |
\\s | Any whitespace (space, \\t, \\n) | /\\s/.test(' ') β true |
\\S | Any non-whitespace character | /\\S/.test('a') β true |
. Character\\n)s flag to include newlinesconst regex = /./;
console.log(regex.test("a")); // true
console.log(regex.test("\\n")); // false
For advanced Unicode matching, use \\p{...} with the u flag.
const emojiRegex = /\\p{Emoji}/u;
console.log(emojiRegex.test("π")); // true
You can combine ranges, negations, and shorthand classes in a single set:
const regex = /[A-Za-z\\d_]/; // Matches letters, digits, or underscore
console.log(regex.test('Z')); // true
console.log(regex.test('9')); // true
console.log(regex.test('-')); // false
Character classes can be combined with quantifiers to match multiple occurrences:
| Quantifier | Meaning | Example |
|---|---|---|
+ | One or more | /[a-z]+/.test('abc') β true |
* | Zero or more | /[a-z]*/.test('') β true |
? | Zero or one | /[a-z]?/.test('a') β true |
{n,m} | Between n and m times | /[a-z]{2,4}/.test('abc') β true |
Special characters like ., *, [, ] need to be escaped with \\ if you want to match them literally.
console.log("[test]".match(/[\[\]]/g)); // ["[", "]"]Β