slevithan/xregexp

Should throw when using XRegExp.replace with native named capture and numbered backref one higher than number of captures

slevithan opened this issue · 0 comments

Found an edge case bug by reading through the code.

ES2018 added a new trailing groups arg that's passed to replacement functions when the search regex uses native named capture. XRegExp.replace wasn't yet accounting for this if all of the following conditions were in place:

  • Using an ES2018 runtime.
  • Using XRegExp.replace with a search regex that uses named capture and is a native regex (not constructed with XRegExp).
  • The replacement is a string rather than function.
  • The replacement string references a capturing group by number that is exactly one higher than the number of capturing groups in the search regex.

Repro:

XRegExp.replace('a', /(?<n>.)/, '$2');
XRegExp.replace('a', /(?<n>.)/, '$02');
XRegExp.replace('a', /(?<n>.)/, '$<2>');
XRegExp.replace('a', /(?<n>.)/, '${2}');
XRegExp.replace('a', /(?<n>.)/, '${002}');
// all should throw, but instead return ''

XRegExp replacement text syntax is stricter than native replacement text syntax in order to avoid/highlight unintended user error and avoid cross-browser inconsistencies/bugs. Native 'a'.replace(/(?<n>.)/, '$2') in fact returns '$2', but XRegExp.replace is supposed to improve this by throwing a SyntaxError.