liveBook · Manning

Negative lookbehind

As explained in Secrets of the JavaScript Ninja, Third Edition

A negative lookbehind is a regular-expression assertion that succeeds when its pattern does not match immediately before the current position.

A negative lookbehind lets a regular expression match only when its pattern does not match the text immediately before the current position. It checks right to left from that position; it does not search the entire preceding string unless the pattern is written to do so. 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",
);

Here, (?<!not\s+) excludes “strike” when preceded by “not” and whitespace. The case-insensitive, global replacement uppercases the unnegated order. section 12.6.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains negative assertion, position anchoring, and right-to-left matching, but does not detail engine internals.
Examples
Uses a case-insensitive replacement to uppercase “Strike” unless preceded by “not” and whitespace.
What you can do after
Apply it via JavaScript regular-expression replacement to exclude matches preceded by specified text.
How it connects
Connects lookbehind with lookahead and regular-expression matching.

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.