Skip to content

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.

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",
);

This rule is not configurable.

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.