JS RegExp Assertions

JavaScript RegExp Assertions and Boundaries

Assertions in regular expressions do not match characters themselves. Instead, they assert that a specific condition is true at a particular position in the string (like checking if we are at the beginning of a word, or the end of a line).


1. String Boundaries (^ and $)

These two assertions anchor your search pattern to the exact beginning or end of the string.

Assertion Description
^ Matches the beginning of the string.
$ Matches the end of the string.

Start and End Boundaries

let text = "The cat is in the hat";

// Does the string START with "The"? console.log(/^The/.test(text)); // true

// Does the string END with "hat"? console.log(/hat$/.test(text)); // true

// Does the string END with "cat"? console.log(/cat$/.test(text)); // false

Form Validation: Developers constantly use ^ and $ together to validate exact inputs. For example, /^\d{5}$/ ensures the user's input is exactly 5 digits from start to finish, with no extra characters before or after.


2. Word Boundaries (\b)

The \b assertion matches a word boundary—the exact position where a word character (\w) meets a non-word character (\W), or the start/end of the string.

It is incredibly useful when you want to search for a whole word, and not a fragment of another word!

Word Boundary \b Example

let text = "I am looking for a plan and a plane. Not a planet.";

// We want to replace the word "plan" with "IDEA".

// BAD: This replaces "plan" inside "plane" and "planet" too! console.log(text.replace(/plan/g, "IDEA"));

// GOOD: The \b asserts it must be an independent word console.log(text.replace(/\bplan\b/g, "IDEA"));

(Note: The uppercase \B matches a non-word boundary, ensuring the pattern is found inside another word).


3. Lookahead Assertions ((?=))

Lookaheads allow you to assert that a pattern is followed by another pattern, without actually including that second pattern in the match result.

Assertion Description
X(?=Y) Positive lookahead. Matches X only if it is followed by Y.
X(?!Y) Negative lookahead. Matches X only if it is not followed by Y.

Lookahead Example

let text = "100 USD and 50 EUR and 200 USD";

// Find numbers that are immediately followed by " USD" let match = text.match(/\d+(?= USD)/g);

// It matched the numbers, but DID NOT include " USD" in the result! console.log(match); // ["100", "200"]

Negative Lookahead Example

let text = "100 USD and 50 EUR and 200 USD";

// Find numbers that are NOT followed by " USD" let match = text.match(/\d+(?! USD)/g);

console.log(match); // ["50"]


Exercise

?

Which assertion requires a pattern to be at the absolute end of a string?