Replace & Transform — Regex

replace() returns a new string: without g only the first match is replaced, with g all of them. In the replacement text, $1, $2 are the groups' content…

Mrs. Ratna wants to put her pre-orders into a spreadsheet. By the end of this lesson, our chat turns into this CSV:

name,phone,total
Dina,+447700900123,17000
Bayu,+447700900456,16500
Sari,+447700900461,25500

Yet the chat is messy: prices are written $85, 90 dollars and 75 bucks, and phone numbers come in three styles. The spreadsheet needs one form: amounts in whole cents ($85 is 8500) and +44 phone numbers. The tool is replace(): it finds the part of a text that matches a pattern, then swaps it for something else. It's like "Find and Replace" in Word, except that what you look for is a pattern, and the replacement can be worked out first.

replace() and the g flag

const withoutG = chat.replace(/(?:\+44 ?|0)7\d{3}[- ]?\d{3}[- ]?\d{3}/, "[phone]");
const withG = chat.replace(/(?:\+44 ?|0)7\d{3}[- ]?\d{3}[- ]?\d{3}/g, "[phone]");

console.log(withoutG.match(/\[phone\]/g).length); // 1
console.log(withG.match(/\[phone\]/g).length);    // 3
console.log(withG.split("\n")[2]);
// "[12/03/26 07.20] Bayu: I'll take cheese sticks 1, snowballs 1. How much? mobile [phone]"

The replacement text: $1, $<name>, $&

In the replacement text, a few $ codes mean something special:

Code Replaced with
$& the whole matched text
$1, $2, ... the content of group 1, group 2, ...
$<name> the content of the named group (?<name>...)
$$ a plain $ sign
console.log("2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")); // '15/01/2024'
console.log("Code PO-0412".replace(/PO-\d{4}/, "[$&]"));                  // 'Code [PO-0412]'
console.log("Total 85".replace(/\d+/, "$$$&"));                            // 'Total $85'
console.log("[email protected]".replace(/^(.)[^@]*(@.*)$/, "$1***$2")); // 'd***@example.com'

const time = /\[(?<day>\d{2})\/(?<month>\d{2})\/(?<year>\d{2}) (?<hour>\d{2})\.(?<minute>\d{2})\]/g;
console.log(chat.replace(time, "[20$<year>-$<month>-$<day> $<hour>:$<minute>]").split("\n")[0]);
// '[2026-03-12 07:15] Ratna (Admin): Eid cookie PO is open! ...'

A replacement function: prices into numbers

A replacement text can only rearrange. To calculate, pass a function. It is called once for each match, and whatever it returns becomes the replacement.

"Cheese Sticks 90 dollars".replace(/(\d+) (dollars|bucks)/, (...args) => { console.log(args); return ""; });
// ['90 dollars', '90', 'dollars', 14, 'Cheese Sticks 90 dollars']

const price = /\$(\d+)|(\d+) (?:dollars|bucks)\b/g;
const numbers = chat.replace(price, (whole, sign, word) =>
  String((sign || word) * 100)
);
console.log(numbers.split("\n")[0]);
// '... *Tart* 8500/jar, *Cheese Sticks* 9000, *Snowballs* 7500. Code PO-0412'

Upper and lower case

Replacement functions also change letter case:

console.log("hello world javascript".replace(/\b\w/g, (h) => h.toUpperCase())); // 'Hello World Javascript'
console.log("hello world".replace(/(^|\s)(\w)/g, (_, p1, p2) => p1 + p2.toUpperCase())); // 'Hello World'

const tidyCase = chat.replace(/\b[A-Z]{4,}\b/g, (word) => word[0] + word.slice(1).toLowerCase());
console.log(tidyCase.split("\n")[4]);
// '[12/03/26 07.25] Sari: Tart 3 jars = 255 dollars right? my no. 07700900461, deliver on 25/03'

From chat to CSV

Now it all comes together: tidy the prices and the phone numbers (the phone pattern from the lesson Common Patterns: URL & Phone), then take each buyer's name, number and total.

const tidy = chat
  .replace(/\$(\d+)|(\d+) (?:dollars|bucks)\b/g, (whole, sign, word) =>
    String((sign || word) * 100))
  .replace(/(?:\+44 ?|0)7\d{3}[- ]?\d{3}[- ]?\d{3}/g, (phone) =>
    phone.replace(/[^\d+]/g, "").replace(/^0/, "+44"));

const csv = ["name,phone,total"];
for (const name of new Set(tidy.match(/(?<=\] )\w+(?=:)/g))) {
  const lines = tidy.match(new RegExp(`^.*\\b${name}\\b.*$`, "gm")).join(" ");
  const phone = lines.match(/\+44\d+/)?.[0] ?? "";
  const total = lines.match(/(?:total|transfer|=) (\d+)/)?.[1] ?? "";
  csv.push(`${name},${phone},${total}`);
}
console.log(csv.join("\n")); // the CSV from the start of the lesson

⚠️ replace() results that catch you out

TL;DR: replace() returns a new string: without g only the first match is replaced, with g all of them. In the replacement text, $1, $2 are the groups' content, $<name> a named group, $& the whole match, $$ a plain dollar: "2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1") gives "15/01/2024", and /^(.)[^@]*(@.*)$/ with "$1***$2" hides an email as d***@example.com. A replacement function receives the whole match and then each group, and what it returns becomes the replacement: use it to calculate (90 dollars into 9000 cents, $85 into 8500) and to change case (/\b\w/g with toUpperCase(), or (_, p1, p2) => p1 + p2.toUpperCase() for /(^|\s)(\w)/g). A few chained replace() calls tidy the chat into a CSV. Don't parse HTML with regex: use a parser.

⚡ replace() and the g flag

Write:

console.log("07700-900-123".replace(/-/g, "")); // '07700900123'

Meaning: Without g, replace() only replaces the first match. It returns a new string; chat itself doesn't change.

⚡ $1 and $2 in the replacement text

Write:

console.log("2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
Guess first: $1 is the year, $3 the day. What is the result?

'15/01/2024'. $1, $2 and $3 are what groups 1, 2 and 3 hold, so the order turns into day/month/year.

Meaning: In the replacement text, $1 and $<name> use what a group holds, $& is the whole match, and $$ a plain dollar sign.

⚡ A replacement function can calculate

Write:

console.log("hello world javascript".replace(/\b\w/g, (h) => h.toUpperCase())); // 'Hello World Javascript'

Meaning: The replacement can be a function: it is called once for each match, and what it returns becomes the replacement. Use it to calculate (90 dollars into 9000 cents) and to change case.

What you will learn