Skip to content

JavaScript Tutorial Regular Expressions

Regex Patterns and Character Classes

Lesson 95 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Literal characters

Most characters match themselves: /cat/ matches the text cat.

Special characters (metacharacters)

Some characters have a special meaning. To match them literally, put a backslash in front: ., *, +, ?, ^, $, (, ), [, ], {, }, |, \.

script.js
JS
console.log(/3.5/.test("3x5"));   // → true   (. matches any character)
console.log(/3\.5/.test("3x5"));  // → false  (\. matches only a real dot)
console.log(/3\.5/.test("3.5"));  // → true

Shorthand character classes

PatternMatches
\da digit (0–9)
\wa “word” character: letter, digit or _
\swhitespace (space, tab, line break)
.any character except a line break
\D, \W, \Sthe opposites
script.js
JS
console.log("Room 42".match(/\d/)[0]);  // → 4
console.log(/\s/.test("two words"));    // → true
console.log(/^\w+$/.test("hello_1"));   // → true
console.log(/^\w+$/.test("hello 1"));   // → false

Your own sets with [ ]

Square brackets match one character from a set.

script.js
JS
console.log(/[aeiou]/.test("sky"));       // → false
console.log(/[aeiou]/.test("sea"));       // → true
console.log(/^[A-Z]/.test("Hello"));      // → true   (range)
console.log(/[^0-9]/.test("123"));        // → false  (^ inside brackets means NOT)

Ranges: [a-z], [A-Z], [0-9], and combinations: [a-zA-Z0-9_].

Anchors: start and end

^ matches the start of the text and $ the end. Without them, a pattern can match anywhere.

script.js
JS
console.log(/cat/.test("concatenate"));    // → true   (found somewhere inside)
console.log(/^cat$/.test("concatenate"));  // → false  (the whole text must be "cat")
console.log(/^cat$/.test("cat"));          // → true

For validation you almost always want ^ and $, so the whole input must match.

Word boundary

\b matches the edge of a word.

script.js
JS
console.log(/\bcat\b/.test("a cat sat"));      // → true
console.log(/\bcat\b/.test("concatenate"));    // → false

Alternatives

| means “or”.

script.js
JS
console.log(/^(red|green|blue)$/.test("green")); // → true
console.log(/^(red|green|blue)$/.test("pink"));  // → false