Mastering Lookbehind Assertions in JavaScript (ES2018)
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.