Anchors in JavaScript

From the JavaScript Regular Expressions cheat sheet · Basic Patterns · verified Jul 2026

Anchors

Matching positions in text

javascript
^       Start of string
$       End of string
\b      Word boundary
\B      Not a word boundary

// Multi-line mode (m flag)
^       Start of line
$       End of line

// Examples
/^hello/.test("hello world")     // true
/world$/.test("hello world")     // true
/^hello$/.test("hello")          // true (exact match)
/\bcat\b/.test("cat in hat")     // true (whole word)
/\bcat\b/.test("scatter")        // false
/\Bcat/.test("scatter")          // true (inside word)

// Multi-line examples
const text = "line1\nline2"
/^line2/m.test(text)             // true (with m flag)
/^line2/.test(text)              // false (without m flag)
💡 Use ^ and $ together for exact full string match
⚡ Word boundary \b is zero-width - doesn't consume characters
📌 Multi-line flag (m) changes ^ and $ behavior
🟢 \b is useful for matching whole words only
anchorsboundaries

Continue with JavaScript Regular Expressions

Save the full cheat sheet or work through every related task.

More JavaScript tasks

Back to the full JavaScript Regular Expressions cheat sheet