Regex Replace: Backreferences and Common Mistakes
Use capture groups to reorder or transform text with JavaScript replacement patterns.
Why this matters
The g flag replaces all matches, while omitting it usually replaces only the first match.
Worked example
Start with this sample input:
Doe, JaneExample result or interpretation (check the linked tool for exact formatting):
(\w+),\s*(\w+) → $2 $1The replacement produces Jane Doe by swapping the second and first captured groups.
Replacement strings have their own syntax
In JavaScript String.replace, $1 refers to the first capture, $2 to the second, and $& to the entire match. The replacement syntax is distinct from the pattern syntax.
JavaScript replacement examples
Swap names
"Doe, Jane".replace(/(\w+),\s*(\w+)/, "$2 $1")Interpretation: Jane Doe
Replace all digits
"a1b2".replace(/\d/g, "#")Interpretation: a#b#
Replace first only
"a1b2".replace(/\d/, "#")Interpretation: a#b2
Always test the replacement on names with spaces, hyphens and non-ASCII letters; \w does not cover every human name.
Step-by-step workflow
- Test the matching pattern before enabling replacement.
- Enter the replacement text and inspect the preview.
- Check punctuation, spacing and repeated matches before using the result.
Try the related ByteKitly tool →
Common mistakes and limitations
Replacement syntax differs between languages; JavaScript uses $1 and $2, not necessarily \1.
Test examples using your own data format and verify results before using them in production systems. ByteKitly's core converters operate in the browser, but avoid sharing confidential input in screenshots or links.