-
Notifications
You must be signed in to change notification settings - Fork 33
RegExp lookbehind assertions #171
Description
Description
Lookarounds are zero-width assertions that match a string without consuming anything. ECMAScript has long supported lookahead assertions that do this in forward direction. Positive lookahead ensures a pattern is followed by another pattern, and negative lookahead ensures a pattern is not followed by another pattern.
ES2018 added support for lookbehind assertions, which are lookarounds that go backwards. Positive lookbehind ensures a pattern is preceded by another pattern, and negative lookbehind ensures a pattern is not preceded by another pattern.
Rationale
Lookbehinds enable developers to ensure that a pattern is or isn’t preceded by another, which is a common use case when dealing with regular expressions — e.g. matching a dollar amount without capturing the dollar sign:
// Positive lookbehind:
const pattern = /(?<=\$)\d+/;
const result = pattern.exec('$42');
// → result[0] === '42'Or, conversely, matching numbers that aren’t dollar amounts:
// Negative lookbehind:
const pattern = /(?<!\$)\d+/;
const result = pattern.exec('€42');
// → result[0] === '42'Unlike many other JavaScript language features, lookbehind support cannot accurately be polyfilled or transpiled. Only interoperable engine-level support can fill the gap.
Chrome 62 (stable in 2017-10) and Firefox 78 (stable in 2020-06) have shipped support, but until all browsers provide support, compatibility issues continue to pop up. Examples:
- steamcommunity.com - Page doesn't load after signing into Steam account · Issue #51385 · webcompat/web-bugs
- “I've hit a website in the wild that uses lookbehind assertions and does not load on Safari.”
- “just hit this bug trying to load a local instance of backstage (https://github.com/backstage/backstage)”
Specification
https://tc39.es/ecma262/#prod-Assertion
Tests
https://test262.report/browse/built-ins/RegExp/lookBehind?engines=javascriptcore%2Cspidermonkey%2Cv8 (corresponding to https://github.com/tc39/test262/tree/main/test/built-ins/RegExp/lookBehind)
Note that since there are no other Interop proposals that need tests from Test262, it would be overkill to set up full Test262 integration just for this one feature. If this proposal is accepted, I volunteer to write equivalent WPT tests for this feature.
Update: web-platform-tests/wpt#37928