# Regular Expressions

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

Subject: JavaScript | Lesson 53 of 63 | 8 min read
Interactive lesson: https://codewithanimation.in/javascript/regular-expressions
Previous: [Memory & Garbage Collection](https://codewithanimation.in/javascript/memory-and-garbage-collection.md) | Next: [Dates, Time & Intl](https://codewithanimation.in/javascript/dates-and-time.md)

## 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'.

## Common mistake: The Readability Problem

The biggest downside of Regex is that it is notoriously difficult to read. A complex regex for validating URLs can look like someone smashed their keyboard.

Always document your complex Regex patterns with comments explaining what each part does. When possible, break them into smaller, named string variables and construct them via `new RegExp()`.

## Tip: Global and Case-Insensitive Flags

By default, regex stops after finding the *first* match, and is highly case-sensitive. Add the `g` (global) flag to find *all* matches in a string, and the `i` (case-insensitive) flag to ignore casing: `/apple/gi`.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/regular-expressions

## Check yourself

### Question 1

What does the regex `/\d+/g` match?

- A. One or more digits, anywhere in the string.
- B. Exactly one digit.
- C. The letter 'd'.

Correct answer: A

`\d` targets digits, `+` specifies 'one or more consecutive', and the `g` flag ensures it finds all occurrences rather than stopping after the first.

- Why not B: Incorrect. The `+` quantifier means 'one or more'.
- Why not C: Incorrect. `\d` is a special character class for digits.

### Question 2

Which JavaScript method returns a simple `true` or `false` if a string matches a regex?

- A. regex.test(string)
- B. string.match(regex)
- C. regex.includes(string)

Correct answer: A

Use `.test()` when you just need to know if a pattern exists (like form validation). Use `.match()` when you actually need to extract the matching text.

- Why not B: Incorrect. `match()` returns an array of matches, or null.
- Why not C: Incorrect. `includes()` is a string method, not a regex method.

### Question 3

What does the pattern `/^Hello/` enforce?

- A. The string MUST start with the word 'Hello'.
- B. The word 'Hello' must be in uppercase.
- C. It excludes the word 'Hello'.

Correct answer: A

The `^` anchor locks the match to the very beginning of the string. Similarly, the `$` anchor locks the match to the very end of the string.

- Why not B: Incorrect. The `^` symbol represents the start of the string, not casing.
- Why not C: Incorrect. While `^` inside brackets `[^a]` means 'not', outside brackets it means 'start of string'.

## 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.
