J

JavaScript Handbook

Clean • Professional

RegEx Character Classes in JavaScript

2 minute

Regular Expression Character Classes

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.

1. Basic Character Classes

Character classes let you match any one character from a specified set or range.

SyntaxDescriptionExample
[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"]

2. Negated Character Class

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

3. Predefined Shorthand Character Classes

JavaScript provides shortcuts for commonly used character sets:

SyntaxMatchesExample
\\dAny digit [0-9]/\\d/.test('5')true
\\DAny non-digit [^0-9]/\\D/.test('a')true
\\wAny word character [a-zA-Z0-9_]/\\w/.test('G')true
\\WAny non-word character/\\W/.test('@')true
\\sAny whitespace (space, \\t, \\n)/\\s/.test(' ')true
\\SAny non-whitespace character/\\S/.test('a')true

4. Dot . Character

  • Matches any character except newline (\\n)
  • Use the s flag to include newlines
const regex = /./;
console.log(regex.test("a")); // true
console.log(regex.test("\\n")); // false

5. Unicode Property Escapes (ES2018+)

For advanced Unicode matching, use \\p{...} with the u flag.

const emojiRegex = /\\p{Emoji}/u;
console.log(emojiRegex.test("😊")); // true

6. Combining Character Classes

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

7. Character Class Quantifiers

Character classes can be combined with quantifiers to match multiple occurrences:

QuantifierMeaningExample
+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

8. Escaping Special Characters

Special characters like ., *, [, ] need to be escaped with \\ if you want to match them literally.

console.log("[test]".match(/[\[\]]/g)); // ["[", "]"]

 

Article 0 of 0