Concept
Anchors: ^ and $ Explained
Anchors match positions, not characters. ^ asserts the start of the string (or line, with the m flag) and $ asserts the end.
What they do
An anchor is a zero-width assertion — it matches a position between characters rather than a character itself. ^ matches the position before the first character of the input. $ matches the position after the last character. They are the primary tool for whole-string validation: wrap a pattern in ^…$ and it only matches if the ENTIRE string conforms.
Whole-string vs. anywhere matching
Without anchors, a regex matches any substring. With ^ and $ at both ends, it only matches when the full input fits the pattern. This is the difference between 'find a digit somewhere' and 'the whole input is exactly digits.'
With the multiline (m) flag
When the m flag is set, ^ and $ also match at the start and end of each line within the input (around every \n). Without m, they only match at the absolute start and end of the string.
Common uses
Form input validation (require the entire value to match), parsing line-oriented formats like log files (with m), and rejecting leading/trailing whitespace when trimming wasn't done upstream.
Related patterns
Strong Password
Enforce strong passwords: min 8 chars, at least one lowercase, uppercase, digit, and special character.
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=…/URL Slug
Validate URL slugs: lowercase letters and digits separated by single hyphens, no leading/trailing hyphens.
/^[a-z0-9]+(?:-[a-z0-9]+)*$/Integer
Matches whole integers, including negative numbers.
/^-?\d+$/