Sikau

Advanced JavaScript · Day 16 · about 25 min

Regex in practice

Capture groups and smart replacing.

Pull out the parts

Finding a date is useful; pulling out its day, month and year is better. Capture groups grab parts of a match, and replace can rearrange them.

Groups and named groups

const date = "2026-10-21";
const m = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(m[1], m[2], m[3]);

const named = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(named.groups.day);

console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
const prices = "momo 180, chiya 40, lassi 90";
const taxed = prices.replace(/\d+/g, (n) => Math.round(n * 1.13));
console.log(taxed);

for (const [, item, price] of prices.matchAll(/(\w+) (\d+)/g)) {
  console.log(item, "→", price);
}

The rest of this lesson

  • Replacing with groups and functionsexplain
  • Predict the outputpredict
  • Swap the namespredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript