Regular Expressions

Intermediate · 17 min

Pattern syntax for matching text — classes, quantifiers, and groups — plus the methods that run a pattern and the gotchas that catch almost everyone once.

Before thisValues, Types, and CoercionStrings and Unicode

freeCodeCamp.org · 17 min

Regular Expressions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by freeCodeCamp.orgReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A regex is a pattern written as a literal (`/abc/`) or built with `new RegExp(str)` — use the constructor whenever the pattern itself comes from a variable, since a literal can't be assembled from a string at runtime.
  • Character classes (`\d`, `\w`, `\s`, `[abc]`), quantifiers (`*`, `+`, `?`, `{n,m}`), anchors (`^`, `$`), and groups (`(...)`) combine into one small language for describing shapes of text rather than exact text.
  • `test()` answers yes/no, `exec()` and `String.match()` return the actual match (and capture groups), and `String.replace()` swaps matched text out — pick the method based on what you need back, not habit.
  • Quantifiers are greedy by default, grabbing the longest match possible; adding `?` after one (`.*?`) makes it lazy, stopping at the first thing that satisfies the pattern instead of the last.
  • A regex with the global flag (`/.../g`) carries state between calls — its `lastIndex` property remembers where the last match ended, which means reusing the same global regex object across unrelated strings produces wrong results unless you reset `lastIndex` or avoid reuse entirely.

Why strings need their own pattern language

Checking whether a string equals another string is easy — === handles that. The problem regex solves is checking whether a string looks like something: a valid email shape, a phone number with any formatting, a word boundary in the middle of a sentence. Writing that kind of check with plain string methods (indexOf, slice, nested loops) turns into a mess fast, because you’re describing a shape, not a fixed value.

A regular expression is a small, separate language for describing shapes of text. Once you can read one, you can validate input, pull data out of a log line, or do a search-and-replace that plain substring matching could never express — all in one line instead of a hand-rolled parser.

Writing one down

A regex is either a literal, delimited by slashes, or built from a string using the constructor:

const literal = /\d{3}-\d{4}/;
const fromString = new RegExp("\\d{3}-\\d{4}");

The literal form is what you reach for almost always — it’s parsed once, up front, and reads cleanly. The constructor form exists for the one case the literal can’t handle: when the pattern itself is only known at runtime, assembled from a variable or user input.

The core syntax

A handful of building blocks cover most real patterns:

  • Character classes describe what a single character can be: \d (digit), \w (word character), \s (whitespace), or a custom set like [aeiou].
  • Quantifiers describe repetition: * (zero or more), + (one or more), ? (zero or one), {n,m} (between n and m times).
  • Anchors pin a match to a position rather than a character: ^ for the start of the string, $ for the end.
  • Groups (...) capture a piece of the match so you can pull it out separately, and let you apply a quantifier to a whole chunk of pattern at once rather than just one character.

The video builds exactly this vocabulary from scratch and is the right place to see each piece in a live example rather than as an abstract list — watching a pattern get assembled piece by piece is how this actually clicks.

Running a pattern against text

Writing a pattern is only half of it; JavaScript gives you several ways to actually use one, and which you pick depends on what you need back:

const re = /\d+/;
re.test("room 42");            // true — just a yes/no
re.exec("room 42");            // ["42", index: 5, ...] — the match itself
"room 42".match(re);           // same shape as exec, called on the string
"room 42".replace(re, "N/A");  // "room N/A" — swap the match out

test() is for a boolean check — does this match anywhere, full stop. exec() and match() hand back the matched text itself, plus any capture groups from parentheses in the pattern. replace() takes the match and substitutes something else in its place, including a function as the replacement for cases where the substitution depends on what was matched.

The two gotchas that catch almost everyone once

Greedy versus lazy. A quantifier grabs as much text as it can while still letting the whole pattern succeed. Against <b>bold</b>, the pattern <.+> matches the entire string, not just <b>, because + is greedy — it reaches for the last > it can find. Add a ? after the quantifier (<.+?>) to make it lazy instead, stopping at the first thing that satisfies the pattern.

Global flag statefulness. A regex built with the g flag remembers where it left off between calls, via its lastIndex property. That’s useful for walking through every match in a string one at a time in a loop — but it means reusing the same global regex object against a different string, without resetting lastIndex, picks up searching from the wrong spot and produces results that look like the pattern itself is broken. It isn’t; the object just has memory you forgot about.

Where this fits

Regex sits in this group because it’s a language-level tool, not tied to any particular API — the same patterns work whether you’re validating a form field in the browser, checking a log line in a Node script, or writing a build tool. It leans on string and type fundamentals from earlier in this roadmap, and from here on you’ll see it show up anywhere text needs validating or reshaping, well outside JavaScript’s own borders.

Check yourself

  1. 01When would you use `new RegExp("...")` instead of a regex literal like `/.../`?

    Whenever the pattern isn't known until runtime — built from a variable, user input, or a value assembled in code. A regex literal is fixed text parsed once when the script loads, so it can't incorporate a value that doesn't exist yet at that point.

  2. 02What's the difference between what `test()` and `exec()` return, and when would you reach for each?

    `test()` returns a plain boolean — did the pattern match anywhere in the string. `exec()` returns the actual match details (the matched text, its index, and any capture groups) or `null` if nothing matched. Use `test()` for a yes/no check like form validation; use `exec()` (or `String.match()`) when you need the matched substring itself.

  3. 03Given the pattern `/<.+>/` against the string `<b>bold</b>`, what does it match, and why might that surprise someone expecting it to match just `<b>`?

    It matches the entire `<b>bold</b>`, because `+` is greedy by default — it grabs as much as possible while still letting the overall pattern succeed, so it reaches all the way to the last `>` in the string rather than stopping at the first one. Using `<.+?>` (lazy) would stop at the first `>` and match just `<b>`.

  4. 04You call `pattern.exec(someString)` in a loop using a regex created with the `g` flag, and after the string changes between iterations the matches come back wrong or skip unexpectedly. What's going on?

    A global regex object keeps state in its `lastIndex` property, remembering where the previous match ended so the next call picks up from there. If you reuse that same regex object against a different string without resetting `lastIndex` to 0 first, it starts searching from the wrong position — this is a common source of regex bugs that look like the pattern itself is broken when it isn't.

  5. 05Why does a regex engine need both character classes and quantifiers — what would be missing with just one or the other?

    A character class (like `\d` or `[a-z]`) describes what a single position in the text can look like, but says nothing about how many times. A quantifier (like `+` or `{3,5}`) describes repetition, but needs something to repeat. Together, `\d{3}` says "exactly three digits in a row" — neither piece alone can express that.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark