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

















