Script Valley
Regex: Actually Useful Patterns
Regex FundamentalsLesson 1.4

Anchors caret and dollar sign in regex

start anchor, end anchor, whole-string matching, multiline flag, word boundary \b, anchor use cases

Anchors Assert Position, Not Characters

Regex anchors

Without anchors, a pattern can match anywhere in the string. Anchors force the match to occur at a specific position.

  • ^ — must match at the start of the string
  • $ — must match at the end of the string
/^hello/.test('hello world') // true  — starts with hello
/^hello/.test('say hello')   // false — hello not at start

/world$/.test('hello world') // true  — ends with world
/world$/.test('worldwide')   // false — more chars after world

/^\d{5}$/.test('90210')     // true  — exactly 5 digits
/^\d{5}$/.test('9021X')     // false
/^\d{5}$/.test('902100')    // false — 6 digits

Word Boundary \b

\b matches the boundary between a word character and a non-word character. Useful for matching whole words without anchoring the whole string.

/\bcat\b/.test('the cat sat') // true
/\bcat\b/.test('concatenate') // false — 'cat' is inside a word

Multiline Flag

With the m flag, ^ and $ match at the start and end of each line, not just the whole string. Essential when processing multi-line input like logs or config files.

/^error/m.test('info ok\nerror found') // true

A common mistake is using ^ for validation without $. The pattern /^\d{5}/ passes '90210abc' because it only checks that the string starts with 5 digits, not that it contains only 5 digits. For form validation, always pair both anchors. The \b word boundary is particularly useful in text search scenarios where you want whole-word matches without anchoring the entire string, such as finding all occurrences of a specific command or identifier in a log file or document.

Up next

Regex flags global case-insensitive multiline explained

Sign in to track progress