Explain Codes LogoExplain Codes Logo

How to replace captured groups only?

javascript
regex
advanced-techniques
performance
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

Efficiently replace captured groups in a string by utilizing the replace() method with a regex pattern incorporating parentheses for groupings and a replacement function. The replacement function specifically targets and reorders these groups.

Example:

const str = "123-456"; // Queue "Freaky Friday" music 🎵 const swapped = str.replace(/(\d+)-(\d+)/, (match, g1, g2) => `${g2}-${g1}`); console.log(swapped); // "456-123"

Here, (\d+) captures digits before and after the dash, while g1 and g2 are these groups, like actors in a play, rewritten against the script.

Advanced techniques: because you want to be the regex ninja

Simple replacements are like newbie levels in a game. Prepare for boss levels with advanced replacement techniques.

Lookahead and lookbehind: not all browsers have your back

In modern JavaScript environments, lookaheads and lookbehinds rule. They allow you to ensure the right condition is met without including unnecessary characters in your captured group.

const str = "Order #123, ID #456"; // Because who needs numbers when you have XYZ? const replaced = str.replace(/(?<=#)\d+/g, "XYZ"); console.log(replaced); // "Order #XYZ, ID #XYZ"

But remember, some older browsers might not support lookbehinds. Be sure to check the compatibility of different features!

Transformation functions: level up your capture-group game

Regex transformer functions help in controlling the replacement process, especially for multiple capture groups.

const str = "Today is 2023-03-15"; // Surprise the American software by doing the date the European way! const formatted = str.replace(/(\d{4})-(\d{2})-(\d{2})/, (match, year, month, day) => `${day}/${month}/${year}`); console.log(formatted); // "Today is 15/03/2023"

Beyond regex: the string game

For replacements too complex for regex alone to handle, split your strings into arrays and rejoin them.

const str = "CamelCaseString"; // Let's impersonate a snake for a while. Hiss... const result = str .split(/(?=[A-Z])/) .map(word => word.toLowerCase()) .join('_'); console.log(result); // "camel_case_string"

Look at that smooth snake_case!

Mastering the regex battlefield

Mastering regex is not just about knowing the syntax, it's about outsmarting it. Here are a few strategies for nailing capturing groups in any situation.

The invisible force: non-capturing groups

Use non-capturing groups (?:...) when you need the group for matching but not capturing. Now, you see it, now you don't!

From "match" to "group": keep an array in your arsenal

Sometimes, you need a little more than .replace(). When replacing is not enough, use .match() with array manipulation to have full control over your captured groups.

The lazy ones: reluctant quantifiers

Want to keep things to the minimum? Make your regex lazy with ?. No more greedy patterns running away with your code!

const str = "<div>Hello</div><div>World</div>"; // Articles seem to be more fashionable these days! const replaced = str.replace(/<div>(.*?)<\/div>/g, "<p>$1</p>"); console.log(replaced); // "<p>Hello</p><p>World</p>"

Wave the 'g' flag: global patterns for the win

Your regex needs a "call to action". Using the 'g' flag ensures every part of the string that matches the pattern gets its spotlight—and replacement.

Boss level: visualisation

Just as in a video game, converting the abstract concept into a visual playground makes it easier to navigate through the world of regex.

Origins: [🧵"Hello"🧵, " ", 🧵"World"🧵] Transformation: **"Hello"** -> **"Hi"**, **"World"** -> **"Universe"**

Your regex game:

const string = "Hello World"; // World, say Hi to your new Universe! const newString = string.replace(/(Hello)|(World)/g, (match, p1, p2) => { if (p1) return "Hi"; if (p2) return "Universe"; }); console.log(newString); // "Hi Universe"

Look, only the patches are tweaked, the string remains intact. Gear up, your regex game level just leveled up!

Nitty-gritty: the devil is in the details

Regex is a realm of peculiarities. Mastery means reading between the lines. Here's a handful of tips specific to regex nuances.

Need for speed: benchmark and test

When it comes to performance, speed is paramount. Benchmarking tools and code snippets help perform speed checks and offer side-by-side comparisons.

Knowledge is power: study your regex

Like a wizard with his scrolls, keep important resources and documentation close. Untangle the webs of regex complexities with them.

Map your territories: regular expression testers

With regex testers like regex101 and jex.im, you can visualize the regex landscape and assess the damage (well, matches) swiftly.

Keep it clean: readability matters

Simplicity fosters maintainability. While regex can turn complex, strive for readability. Comment complicated patterns—your future self will thank you.