liveBook · Manning

Lookbehind assertion

As explained in Secrets of the JavaScript Ninja, Third Edition

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

A lookbehind is a zero-length regular-expression assertion: it checks text before the current position without consuming that text. Use it to require or exclude preceding text while matching at the current position. section 12.6 section 12.6.2

Positive lookbehind uses (?<=pattern); negative lookbehind uses (?<!pattern). The pattern must match immediately before the current position—not merely somewhere earlier in the string. section 12.6.2

const kebabCaseRegex = /(?<=[a-z])-([a-z])/g

This pattern matches a hyphen and following lowercase letter only when a lowercase letter immediately precedes the hyphen. section 12.6.2

Mask characters after each name’s first letter

The pattern /(?<=\w)\w/g replaces each word character preceded by another word character. Applied to “Hattori Sato”, it leaves the first letter of each name visible and replaces the rest with asterisks. section 12.6.2

Exclude a negated command

The pattern /(?<!not\s+)strike/gi matches “strike” unless it is preceded by “not” and whitespace, so a replacement can emphasize “Strike at dawn” but leave “do not strike” unchanged. section 12.6.2

Lookbehind assertions were added in ES2018. Regular expressions using them fail in runtimes without support; transpilation does not make them work there. section 1.1.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains positive and negative syntax, immediate-position anchoring, and matching through worked examples.
Examples
Uses kebab-case filtering, masking characters in names, and excluding negated strike commands.
What you can do after
Apply it via JavaScript regular expressions to match or replace text according to what immediately precedes it.
How it connects
Connects lookbehind to zero-length assertions, lookahead, regular expressions, and string replacement.

Also explained in

Compare how 2 books explain lookbehind 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.