Anchors
Everything so far matched characters. Anchors match positions — places between characters. They consume no text; they only assert that the match is at a certain spot.
| Anchor | Matches the position… |
|---|---|
^ |
at the start of the input (with m: at the start of every line) |
$ |
at the end of the input (with m: at the end of every line) |
\b |
at a word boundary (next lesson) |
\B |
anywhere that is not a word boundary |
Python, Java, .NET and others also offer \A (very start) and \z / \Z (very end), which ignore multiline mode. JavaScript does not have them.
^ — start
/^\d+/g
42 apples and 7 pears1 match
#1 "42" at index 0
Without ^ the pattern would also find 7. With ^, a match is only allowed at index 0.
$ — end
/\d+$/g
42 apples and 7 pears 991 match
#1 "99" at index 22
Both: validating a whole string
Anchors are what turn a search pattern into a validation pattern. \d{5} finds five digits somewhere; ^\d{5}$ requires the entire input to be five digits:
const zip = /^\d{5}$/;
for (const s of ["70000", "7000", "700001", "zip 70000"]) {
console.log(JSON.stringify(s), zip.test(s));
}
console.log(/\d{5}/.test("zip 700001"));"70000" true
"7000" false
"700001" false
"zip 70000" false
true
Tip: Forgetting anchors is the most common bug in validation regexes. If you want "the whole string looks like X", write
^X$.
Multiline mode: the m flag
With several lines of text, ^ and $ normally still refer to the start and end of the whole input. The m flag changes them to match at the start and end of each line:
/^\w+/g
alpha one
beta two
gamma three1 match
#1 "alpha" at index 0
/^\w+/gm
alpha one
beta two
gamma three3 matches
#1 "alpha" at index 0
#2 "beta" at index 10
#3 "gamma" at index 19
A typical use: find lines that end with a particular word.
/^.*TODO$/gm
fix login TODO
write tests
update docs TODO2 matches
#1 "fix login TODO" at index 0
#2 "update docs TODO" at index 27
^ means two different things
Don't confuse the anchor ^ (outside brackets) with the negation ^ (first character inside brackets):
| Pattern | Meaning |
|---|---|
^a |
an a at the start |
[^a] |
any character except a |
^[^a] |
a first character that is not a |
Anchors are zero-width
Because anchors match positions, ^ and $ alone produce an empty match:
/$/g
abc1 match
#1 "" at index 3
That's handy in code — for example "abc".replace(/^/, "> ") adds a prefix, and with the gm flags it prefixes every line:
const text = "first\nsecond\nthird";
console.log(text.replace(/^/gm, "> "));> first
> second
> third
Test yourself
Which pattern checks that a whole string consists only of letters?
/[a-z]+/i/^[a-z]+$/i/[^a-z]/i/$[a-z]+^/i
What does the m flag change?
.matches newlines^and$match at line starts and ends- Matching is case-insensitive
- Multiple matches are returned
How many characters does ^ consume?
- 0
- 1
- The whole first line
- It depends on the flags