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

