Course contentsShow
← JavaScript
Lesson 1689 of 2,72336. Regular ExpressionsFree lesson

Line Start and End: ^ and $

Learn how ^ matches the start of a line and $ matches the end, controlling where patterns must appear.

Line Start and End: ^ and $

You'll learn how to anchor regex patterns to match only at the very beginning or end of a line.

What Are Anchors?

The ^ (caret) and $ (dollar sign) metacharacters don't match actual characters—they match positions. Think of them as invisible boundary markers:

  • ^ asserts "this pattern must start right here, at the beginning of the line"
  • $ asserts "this pattern must end right here, at the end of the line"

They're like putting bookends on a shelf: the bookends don't change what's between them, but they define where things must start and stop.

Matching from the Start

const startsWithHello = /^Hello/;

startsWithHello.test("Hello world");  // true
startsWithHello.test("Say Hello");    // false (Hello not at start)
startsWithHello.test("Hello");        // true

Matching at the End

const endsWithBye = /Bye$/;

endsWithBye.test("Goodbye Bye");   // true
endsWithBye.test("Bye everyone");  // false (Bye not at end)
endsWithBye.test("Bye");           // true

Combining Both Anchors

const exactMatch = /^exact$/;

exactMatch.test("exact");          // true
exactMatch.test("exact match");    // false (extra text at end)
exactMatch.test("not exact");      // false (extra text at start)

When you use both ^ and $ together, you're saying "match this pattern and nothing else"—the entire line must be exactly what you specified.

Multiline Behavior

Remember the m flag you learned? It changes how ^ and $ behave with multi-line strings, making them match the start/end of each line instead of just the entire string.

Key Takeaway: ^ anchors patterns to the line start, $ to the line end, and together they enforce exact matches—controlling where your pattern must appear, not what it matches.