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]"
- Without the
gflag,replace()only replaces the first match: Dina's number. Bayu's and Sari's stay visible. Withg, every match is replaced. - A plain text pattern also replaces only the first:
"07700-900-123".replace("-", "")gives'07700900-123'. For all of them:/-/g, orreplaceAll("-", ""). replace()doesn't changechat. Strings in JavaScript can't be changed, so it returns a new string. Keep the result in a variable.
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! ...'
$3/$2/$1rearranges three groups: year-month-day becomes day/month/year.- Hiding an email:
(.)captures the first letter,[^@]*the rest of the name before the@(not captured),(@.*)the@up to the end. The replacement is the first letter, three stars, then the domain. - The chat's time
[12/03/26 07.15]becomes[2026-03-12 07:15]through named groups:$<year>reads more easily than$3.
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'
- The function's arguments, in order: the whole match, the content of each group, its position (
14), then the whole text. When the pattern has named groups, one more argument comes at the end: thegroupsobject. - The price pattern has two choices.
$85matches the left choice:signholds'85',wordholdsundefined.90 dollarsmatches the right choice:signisundefined,wordis'90'.sign || wordtakes the group that matched, and it's multiplied by 100 into cents. - What the function returns is turned into text.
String(...)says so openly.
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'
\b\wmatches the first letter of each word, so only that letter is raised. The rest is left alone.(^|\s)(\w): group 1 is the start of the text or a space, group 2 the word's first letter._is just a name for the first argument (the whole match), which isn't used.[A-Z]{4,}takes all-capital words of at least 4 letters:TARTbecomesTart. A short abbreviation likePOis safe.
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
- Two chained
replace()calls: the result of the first is the text for the second. (?<=\] )\w+(?=:)takes the sender's name:Dina,Bayu,Sari.Ratna (Admin)is left out, because a space and a parenthesis come before the colon.- Each name gathers every line that mentions it, including the admin's
@Bayu total 16500, and the number and total are taken from there. - Without the tidying step the CSV breaks: the number
+44 7700-900-456doesn't match\+44\d+because of the space, aftertransferintransfer $170comes a$, not a digit, and from255 dollarsonly255is taken, in dollars instead of cents. Whatever isn't found becomes empty text through?.[0] ?? "", not an error.
⚠️ replace() results that catch you out
- Forgetting
g. Only the first match is replaced, and the rest slips through without an error. - Forgetting
returnin a function with curly braces."90 dollars".replace(/(\d+) dollars/, (whole, n) => { n * 100; })gives'undefined'. Writereturn, or use the short form without braces. $in the replacement text.$1,$&and$<name>mean something special. Want a plain dollar sign? Write$$.- A case-changing pattern that is too wide.
\b[A-Z]{2,}\balso turnsPO-0412intoPo-0412. - Parsing HTML with regex.
"<p>Hello <b>Dina</b></p>".replace(/<[^>]*>/g, "")gives'Hello Dina', but'<p title="a>b">Hello</p>'becomes'b">Hello'. HTML has a nested structure and marks whose meaning depends on context (inside an attribute, a comment, a script), and a regex can't keep track of that. Use a parser:DOMParserin the browser, and DOMPurify to clean HTML from users.
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.