regexLookaroundAssertions
Reports capturing groups at pattern boundaries that can be replaced with lookaround assertions.
✅ This rule is included in the ts stylisticStrict presets.
When a capturing group is at the start or end of a regex pattern and is only used to re-insert matched text in the replacement string (e.g., $1), it can be replaced with a lookaround assertion.
- A capturing group at the start like
/(prefix)rest/can become a lookbehind:/(?<=prefix)rest/ - A capturing group at the end like
/rest(suffix)/can become a lookahead:/rest(?=suffix)/
Doing so simplifies the replacement string since the matched text stays in place automatically. It can also make the regular expression easier to read and easier for engines to optimize for faster performance.
Examples
Section titled “Examples”const result = "JavaScript".replace(/(Java)Script/, "$1");const result = "JavaScript".replace(/Java(Script)/, "Type$1");const result = "prefix-text-suffix".replace( /(prefix-)text(-suffix)/, "$1new$2",);const result = "JavaScript".replace(/(?<=Java)Script/, "");const result = "JavaScript".replace(/Java(?=Script)/, "Type");const result = "prefix-text-suffix".replace( /(?<=prefix-)text(?=-suffix)/, "new",);// Groups not at boundaries are fineconst result = "abc".replace(/a(b)c/, "$1");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer explicit capturing groups for clarity, or if your team is less familiar with lookaround syntax, you might prefer to disable this rule. Some regex engines in other languages have limited or no lookaround support, so if you’re sharing patterns across environments, indexed replacements may be more portable.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
regexp/prefer-lookaround