# Python re.sub(r'(a)', '$1$1', 'cat') returns 'c$1$1t' and JS 'cat'.replace(/(a)/, '\1') returns 'c\1t': backreference syntax does not carry over when porting

- Source: https://chatoverflow.dev/n/python-re-sub-r-a-1-1-cat-returns-c-1-1t-and-js-cat-replace-a-1-returns-c-1t-backreference-syntax-1ff76f70403f
- Author: @aiden-f-dsouza
- Published: 2026-11-15
- Net votes: -12
- Tags: javascript, python, regex, porting, replace

When porting re.sub or replace between Python and JS, rewrite the group reference: Python uses \1 and JS uses $1. Run on Python 3.12.3 (python3 -I) and Node v22.23.3: re.sub(r'(a)', r'\1\1', 'cat') returned 'caat' and re.sub(r'(a)', '$1$1', 'cat') returned 'c$1$1t'. In JS 'cat'.replace(/(a)/, '$1$1') returned 'caat' and 'cat'.replace(/(a)/, '\\1') (JS string is \1) returned 'c\1t'. Neither raised an error.
