Reorder a date with regex capture groups in JavaScript
Intermediate · 4 min read
Dates often arrive in one format and need to be shown in another. A database stores '2025-04-09' (year, month, day), but a reader in Lagos or London expects '09/04/2025' (day, month, year). You could split the string and glue the parts back in a new order, but replace can do it in one line by remembering parts of the match.
In this tutorial you will reorder a date with capture groups, then learn the other special $ patterns you can use in a replacement: $&, $$ and named groups. You should know how replace works with a regular expression. Groups are explained below.
Capture groups
In a regular expression, round brackets ( ) make a capture group. The pattern still matches as before, but the text inside each pair of brackets is remembered. Groups are numbered from left to right, starting at 1.
For a date we need three groups: four digits, a dash, two digits, a dash, two digits. [0-9] matches one digit, and {4} after it means "exactly four of those". So the pattern is:
([0-9]{4})-([0-9]{2})-([0-9]{2})
group 1 group 2 group 3
Using groups in the replacement
In the replacement string, $1 means "whatever group 1 matched", $2 means group 2, and so on. So the replacement '$3/$2/$1' puts the day first, then the month, then the year, with slashes between.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
28 The $ patterns in a replacement
fairReorder '2025-04-09' into '09/04/2025' using capture groups in the replacement. Then find out what $&, $$ and $<name> mean.
Stuck? Three hints, smallest first
- 1.
$1,$2and$3refer to the capture groups, in order. - 2.
$&is the whole match;$$is a literal dollar sign. - 3. A group number that does not exist is left in the output as plain text.
Step 1: reorder the date
const swapDate = (text) => text.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, '$3/$2/$1');
console.log(swapDate('2025-04-09')); // '09/04/2025'
The regex matched the whole date. Group 1 is 2025, group 2 is 04, group 3 is 09. The replacement rebuilt the date from those pieces in a new order.
Step 2: the whole match with $&
$& means the whole matched text. It is how you wrap a match in something:
console.log('lagos'.replace(/lagos/, '[$&]')); // '[lagos]'
console.log('a b'.replace(/[a-z]/g, '[$&]')); // '[a] [b]'
[a-z] matches one lowercase letter. With the g flag every letter is wrapped. Without it, only the first would be.
Step 3: a real dollar sign
Because $ starts these patterns, you need $$ to get one dollar sign in the output:
console.log('x'.replace(/x/, '$$')); // '$'
Forget this, and a replacement that happens to contain $& or $1 comes out as something other than what you typed.
Step 4: named groups
Numbers get confusing once a pattern has several groups. You can name a group by writing ?<name> just inside its opening bracket, and then use $<name> in the replacement:
const re = /(?<y>[0-9]{4})-(?<m>[0-9]{2})/;
console.log('2025-04'.replace(re, '$<m> of $<y>')); // '04 of 2025'
The pattern matches exactly the same text. The names just make the replacement easier to read.
Step 5: a group that doesn't exist
What if you refer to a group that isn't in the pattern?
console.log('a'.replace(/(a)/, '$2')); // '$2'
console.log('a'.replace(/a/, '$0')); // '$0'
There is only one group, so $2 has nothing to stand for, and it is left in the output as plain text. $0 is not a pattern at all (use $& for the whole match). No error is thrown, so typos here show up only in the output.
Step 6: before and after the match
Two rarer patterns exist. A dollar sign followed by a backtick is everything before the match, and $' is everything after it.
console.log('ab'.replace(/b/, '<$`>')); // 'a<a>'
console.log('ab'.replace(/a/, "<$'>")); // '<b>b'
You will seldom need them. They are worth knowing so a backtick or apostrophe after a $ in a replacement doesn't surprise you.
Step 7: group a phone number
Here is the same idea on a different job. Split an 11-digit number into groups of 4, 3 and 4:
const phone = '08031234567'.replace(/([0-9]{4})([0-9]{3})([0-9]{4})/, '$1 $2 $3');
console.log(phone); // '0803 123 4567'
The full solution
Here is the complete answer: swapDate, then a check for each $ pattern from this lesson. Press Run to see the reordered date and the wrapped match.
const swapDate = (text) => text.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, '$3/$2/$1');
console.log('swapDate:', swapDate('2025-04-09'));
console.log("'lagos'.replace(/lagos/, '[$&]') :", 'lagos'.replace(/lagos/, '[$&]'));
console.log("'a'.replace(/(a)/, '$2') :", 'a'.replace(/(a)/, '$2'), '<- no group 2, so left as text');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('capture groups can be reordered', swapDate('2025-04-09'), '09/04/2025');
test('$& is the whole match', 'lagos'.replace(/lagos/, '[$&]'), '[lagos]');
test('$` is everything before the match', 'ab'.replace(/b/, '<$`>'), 'a<a>');
test("$' is everything after it", 'ab'.replace(/a/, "<$'>"), '<b>b');
test('$$ is a literal dollar sign', 'x'.replace(/x/, '$$'), '$');
test('a named group is referenced as $<name>', '2025-04'.replace(/(?<y>[0-9]{4})-(?<m>[0-9]{2})/, '$<m> of $<y>'), '04 of 2025');
test('a group number that does not exist stays as text', 'a'.replace(/(a)/, '$2'), '$2');
test('and $0 is not a thing either', 'a'.replace(/a/, '$0'), '$0');
test('grouping a phone number', '08031234567'.replace(/([0-9]{4})([0-9]{3})([0-9]{4})/, '$1 $2 $3'), '0803 123 4567');
test('wrapping every match needs g as well as $&', 'a b'.replace(/[a-z]/g, '[$&]'), '[a] [b]');
$1 is a string, always. There is no way to do arithmetic on a captured group inside a replacement string — for that you need the function form, which is next.
$` and $' (the text before and after the match) are real but almost never useful, and they are worth knowing mainly so that a stray backtick or apostrophe in a replacement does not surprise you. The genuinely important two are $& and $$: the first because wrapping a match is such a common job, the second because forgetting it is how a price ends up as 'the match' instead of '$5'.
Common mistakes
- Forgetting the brackets. Without
( )there are no groups, and$1stays as the text$1. - Expecting maths on a group.
$1is always text. To change a number you need a function as the replacement, covered in the next exercise. - Writing one
$for a dollar sign. Use$$in a replacement string.
Try it yourself
- Turn
'09/04/2025'back into'2025-04-09'. - Swap a name written
'Akbi, Emmanuel'into'Emmanuel Akbi'. - Wrap every number in
'room 9 and room 10'in brackets, so you get'room [9] and room [10]'.