liveBook · Manning

Assertion

As explained in Secrets of the JavaScript Ninja, Third Edition

An assertion is a regular-expression condition that checks surrounding text without consuming it as part of the match.

A regular-expression assertion checks text around the current match position without consuming that text as part of the match. Lookahead checks text to the right; lookbehind checks text to the left. section 12.6.2

Lookbehind can require or rule out a pattern immediately before the current position:

  • Positive lookbehind, `(?<=pattern)`, lets a match proceed when the preceding text satisfies the pattern. section 12.6.2
  • Negative lookbehind, `(?<!pattern)`, lets a match proceed when the preceding text does not satisfy the pattern. section 12.6.2
  • The preceding pattern must fit immediately before the current position; a matching character farther back does not satisfy the assertion. section 12.6.2
const kebabCaseRegex = /(?<=[a-z])-([a-z])/g

This pattern uses positive lookbehind to match a hyphen only when it follows a lowercase letter. section 12.6.2

Listing 12.11 Using a lookbehind to replace non-first letters
const trailingLetterRegex = /(?<=\w)\w/g; #A
const ninja = "Hattori Sato";
const wantedPoster = ninja.replace( #B
  trailingLetterRegex, #B
  "*", #B
); #B

console.assert(
  wantedPoster === "H****** S***",
  "Only the first letter of each name is shown",
);

This replacement uses lookbehind to mask word characters while leaving the first letter of each name visible. section 12.6.2

Listing 12.12 Using a negative lookbehind to check for a preceding word
const realStrikeRegex = /(?<!not\s+)strike/gi; #A
const orders =
  "Strike at dawn, but do not strike at dusk";
const shouted = orders.replace( #B
  realStrikeRegex, #B
  (command) => command.toUpperCase(), #B
); #B

console.assert(
  shouted ===
    "STRIKE at dawn, but do not strike at dusk",
  "Only the order that is not negated is shouted",
);

This pattern uses negative lookbehind to uppercase “strike” only when it is not preceded by “not ”. section 12.6.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains positive and negative lookbehind, immediate anchoring, and worked patterns; mentions lookahead but does not develop it.
Examples
Uses patterns for kebab-case hyphens, masking names, and distinguishing negated from direct commands.
What you can do after
Evaluate and write regular-expression patterns that condition matches on immediately preceding text.
How it connects
Connects lookbehind with lookahead, regular expressions, matching, and replacement.

Also explained in

Compare how 18 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.