CPCODELAB
JavaScript

Regular Expressions Basics

9 min read

Regular Expressions

Regular expressions (regex) are patterns for matching text. They are used for validation, searching, replacing, and extracting parts of strings.

javascript
// Literal syntax /pattern/flags
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const digitRegex = /\d+/g;  // g = global (all matches)

// Test — returns boolean
emailRegex.test("user@example.com"); // true
emailRegex.test("not-an-email");     // false

// match — returns array of matches
"I have 3 cats and 12 dogs".match(digitRegex);
// ["3", "12"]

// replace
"hello world".replace(/o/g, "0"); // "hell0 w0rld"

// Capture groups
const dateStr = "2025-07-24";
const match = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/);
if (match) {
  const [, year, month, day] = match;
  console.log(year, month, day); // 2025 07 24
}

Common Character Classes

  • \d — digit (0–9). \D — non-digit
  • \w — word char (a-z A-Z 0-9 _). \W — non-word
  • \s — whitespace. \S — non-whitespace
  • . — any char except newline
  • ^ — start of string, $ — end of string
  • [abc] — character class, [^abc] — negated
  • {3} — exactly 3, {2,5} — 2 to 5, + — one or more, * — zero or more, ? — optional

Regex can be hard to read. Always add a comment explaining what a complex pattern does. For extremely complex patterns, consider using a dedicated parsing library instead.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises