Boundary Anchors: Matching at Specific Positions
Anchors do not match characters — they match positions within the string.
1. Line Anchors: ^ and $
^(caret): Matches the position at the start of the string or line.$(dollar): Matches the position at the end of the string or line.
// ^ anchor: Only match if string STARTS with "Error"
/^Error/.test("Error: file not found"); // true
/^Error/.test("Fatal Error: disk full"); // false
// $ anchor: Only match if string ENDS with ".js"
/\.js$/.test("index.js"); // true
/\.js$/.test("index.jsx"); // false
// Both anchors: Match the ENTIRE string
/^\d{4}$/.test("2026"); // true (only four digits, nothing else)
/^\d{4}$/.test("20261"); // false (five digits)2. Word Boundary: \b
\b matches the position between a word character (\w) and a non-word character. It is useful for matching whole words without partial matches:
const str = "The cat concatenated the catfish.";
// Without \b: Matches "cat" anywhere (inside "concatenated" too)
str.match(/cat/g); // ["cat", "cat", "cat"]
// With \b: Matches only the standalone word "cat"
str.match(/\bcat\b/g); // ["cat"]3. Combining Anchors with Other Patterns
// Validate an entire string is a valid positive integer (no leading zeros)
/^[1-9]\d*$/.test("1024"); // true
/^[1-9]\d*$/.test("01024"); // false (leading zero)
// Validate entire string is a valid hexadecimal color
/^#[0-9a-fA-F]{6}$/.test("#ff5733"); // true
/^#[0-9a-fA-F]{6}$/.test("#gg5733"); // falsePublished on Last updated: