R

TestRegex

← Back to Blog

Python vs JavaScript Regex: Key Differences You Must Know

Both Python and JavaScript implement flavors of regex that look Perl-like, but they drift apart in edge cases and API design. Here are the "gotchas" that catch every full-stack developer.

1. Backreferences in Replacements

This is the classic mix-up. When you want to use a captured group in a replacement string:

  • Python: Uses \1, \2.
  • JavaScript: Uses $1, $2.
# Python
re.sub(r'(a)', r'\1', 'a')

// JavaScript
'a'.replace(/(a)/, '$1')

2. Flags and Modifiers

Python accepts flags as a second argument to compile/search (e.g., re.I | re.M). JavaScript suffixes them to the regex literal (e.g., /abc/im).

3. Methods

Python's re.match() checks only the start of the string. JavaScript's test() or match() searches anywhere unless anchored.