liveBook · Manning

Lookahead

As explained in Secrets of the JavaScript Ninja, Third Edition

A lookahead is a regular-expression assertion that checks for a pattern immediately after the current position without consuming text.

A lookahead checks whether a pattern matches text immediately after the current position, without consuming that text. It is a zero-length assertion: the surrounding regex can continue matching while the looked-ahead text remains available. section 12.6 section 12.6.1

The positive form is `(?=pattern)`. Think of it as a dry run: if the pattern succeeds, the regex continues; if it fails, the search can try another position. For example, a lookahead can check for a later word while matching a name before it. section 12.6.1

Listing 12.9 Using a lookahead to check whether a pattern comes later
const armedNinjaRegex =
  /[A-Z][a-z]+(?=.*(katana|shuriken))/g; #A
const getArmedNinjaNames = (str: string) => #B
  [...str.matchAll(armedNinjaRegex)].map( #B
    (found) => found[0], #B
  ); #B

const armedNinjaNames = [ #C
  "Hattori carrying a katana", #C
  "Yuri and Eri carry a shuriken", #C
  "Kenji carrying a rice ball", #C
].flatMap(getArmedNinjaNames); #C

console.assert(
  armedNinjaNames.includes("Hattori"),
  "Hattori is an  armed ninja",
);
console.assert(
  armedNinjaNames.includes("Yuri"),
  "Yuri is an  armed ninja",
);
console.assert(
  armedNinjaNames.includes("Eri"),
  "Eri is an  armed ninja",
);
console.assert(
  armedNinjaNames.length === 3,
  "There are no other armed ninjas",
);

This example uses lookahead to find names that occur before “katana” or “shuriken.” section 12.6.1

Listing 12.10 Using a lookahead to format a number
const thousandsRegex = /\d(?=(\d{3})+$)/g; #A
const treasury = "1724000";
const formatted = treasury.replace( #B
  thousandsRegex, #B
  (digit) => `${digit},`, #B
); #B

console.assert(
  formatted === "1,724,000",
  "The shogun's treasury has '1,724,000' ryo",
);

This example inserts thousands separators by matching digits that precede groups of three digits. section 12.6.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains zero-length behavior through stepwise matching examples and practical applications.
Examples
Demonstrates finding names before weapon terms and inserting thousands separators into a number.
What you can do after
Apply lookahead with JavaScript regexes and String.matchAll or String.replace.
How it connects
Connects lookahead to zero-length assertions, lookbehind, global matching, and regular-expression backtracking.

Also explained in

Compare how 2 books explain lookahead →

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.