Regular Expressions

Master the art of pattern matching. Use Regular Expressions to validate emails, extract phone numbers, and manipulate text with extreme precision.

JavaScript8 min readConcept 53 of 63

Pattern Matching

A **Regular Expression** (Regex) is a sequence of characters that forms a search pattern. Instead of searching for an exact word like 'apple', you can search for a pattern like 'any three digits followed by a hyphen'.

In JavaScript, you create them by wrapping the pattern in forward slashes: /pattern/flags.

Validation and Extraction

Regex is the undisputed king of text processing. Why write 20 lines of if/else statements to check if an email is valid when a single regex can validate the format instantly?

It is primarily used for **Validation** (e.g., regex.test(password) returning true or false) and **Extraction** (e.g., text.match(regex) returning an array of all phone numbers found in a giant document).

The Syntax Toolkit

Regex looks like gibberish until you learn the basic toolkit:

- \d matches any digit (0-9). \w matches any word character (a-z, A-Z, 0-9, _).

- + means 'one or more'. * means 'zero or more'. ? means 'optional'.

- {3} means 'exactly three times'.

- ^ means start of string. $ means end of string.

So, /^\d{3}-\d{4}$/ perfectly matches a 7-digit phone number format like '555-1234'.

The Live Matcher

Type a regex pattern below and toggle the 'global' flag. Watch how the matching substrings in the sample text instantly highlight as your pattern takes shape.

1. Define Pattern
//
2. Sample Text
Matches: 2
Call me at 555-1234 or 555-9876 today! My email is test@example.com.
iNotice how the g flag highlights all matches. Try removing the g flag-the engine will stop immediately after finding the very first match!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does the regex `/\d+/g` match?
  2. 2Which JavaScript method returns a simple `true` or `false` if a string matches a regex?
  3. 3What does the pattern `/^Hello/` enforce?

Remember this

  • Regular Expressions are patterns used to match character combinations in strings.
  • Define them using literal syntax /pattern/flags.
  • Use character classes like \d (digit) and \w (word character) instead of typing out ranges.
  • Use quantifiers like + (1 or more) or {n} (exactly n) to control repetition.
  • The g flag finds all matches (global), and the i flag ignores case.
  • Use regex.test(str) for true/false validation, and str.match(regex) for extraction.

Done with this concept?

Mark it complete to track your progress. No login needed.