Mastering Lookbehind Assertions in JavaScript (ES2018)
Executive Summary
- Clarifies the main production use case and where regex fits in the workflow.
- Provides implementation boundaries that prevent over-matching and fragile behavior.
- Highlights testing and rollout practices to reduce regressions.
In Short
Use narrowly scoped regex patterns, validate with fixture-driven tests, and verify behavior in the target engine before deployment.
Example Blocks
Input
Sample input
Expected Output
Expected match or transformed output
Engine Caveats
- Flag semantics vary by engine.
- Named groups and lookbehind support differ across runtimes.
- Replacement syntax is not portable across all languages.
For years, JavaScript developers envied Python and PCRE for their "lookbehind" capabilities. With ES2018, that wait ended. You can now match a pattern only if it is preceded by another pattern.
Positive Lookbehind (?<=...)
This asserts that what precedes the current position is the given pattern, but it doesn't consume characters.
// Match a price amount, but not the dollar sign
const price = "$500";
const regex = /(?<=$)\d+/;
console.log(price.match(regex)); // Output: ["500"]
Negative Lookbehind (?<!...)
Ensures the pattern is not preceded by a specific term.
/(?<!not )feasible/
This matches "feasible" only if the word "not " is not immediately before it.
Browser Compatibility
Support is widespread in modern Node.js (8.10+), Chrome, and Firefox. However, always transpile with Babel if you need to support Internet Explorer (RIP) or very old Safari versions.
Reusable Patterns
FAQ
What problem does this guide solve?
It focuses on a practical regex workflow that can be applied directly in production codebases.
Which regex engines should I verify?
Validate behavior in the exact runtime engines your product uses before rollout.
How do I avoid regressions?
Add explicit passing and failing fixtures in CI for every key pattern introduced in the guide.
Related Guides
Test related patterns in the live editor
Open Editor