Use a function as a replace() callback in JavaScript
Intermediate · 4 min read
Sometimes the new text depends on what you found. You want to add one to every number in a sentence, turn every word into capitals, or number each item as you go. A replacement string can't do any of that, because $1 is only ever a copy of the text. What you need is to run some code for each match.
replace lets you do exactly that: instead of a replacement string, you pass a function. In this tutorial you will add one to every number in a line, learn what the function receives, and see why this form is also the safest way to insert data. You should know how replace works with a regex and the g flag.
A function as an argument
In JavaScript you can pass a function to another function, the same way you pass a number or a string. The receiving function then calls it when it needs to. A function passed like this is often called a callback.
replace calls your function once for every match. Whatever your function returns is used as the replacement for that match.
console.log('ab'.replace(/b/, () => 'X')); // 'aX'
The match is the first argument
Your function is given the matched text as its first argument. So (d) => ... gets each match in d, and can build the replacement from it.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
29 A function as the replacement
fairAdd one to every number in a line of text. A replacement string cannot do arithmetic, so pass a function instead and work out what arguments it receives.
Stuck? Three hints, smallest first
- 1. The function is called once per match and its return value is used as the replacement.
- 2. The arguments are the match, then each capture group, then the offset, then the whole string.
- 3. With named groups, a final object of groups is appended after those.
Step 1: why a string won't do
[0-9]+ matches one or more digits, so it finds whole numbers like 9 and 10. With a string replacement, you can only copy them:
console.log('room 9 and room 10'.replace(/([0-9]+)/g, '$1+1')); // 'room 9+1 and room 10+1'
$1+1 is just text. No sum happens.
Step 2: add one with a function
const bump = (text) => text.replace(/[0-9]+/g, (d) => String(Number(d) + 1));
console.log(bump('room 9 and room 10')); // 'room 10 and room 11'
For each match, the function gets the digits as a string in d. Number(d) turns them into a number, + 1 adds one, and String(...) turns the result back into text. Because of the g flag, the function runs for both numbers.
Step 3: change the matched text
The same pattern works for any change you can write in code:
const shoutWords = (text) => text.replace(/[a-z]+/g, (w) => w.toUpperCase());
console.log(shoutWords('a bc')); // 'A BC'
Step 4: what else the function receives
After the match, the function gets more arguments: each capture group in order, then the offset (the position where the match starts), then the whole original string.
const out = 'ab'.replace(/(a)(b)/, (m, g1, g2, offset) => [m, g1, g2, offset].join('|'));
console.log(out); // 'ab|a|b|0'
The match is ab, group 1 is a, group 2 is b, and it started at position 0. If the pattern has named groups, one more argument arrives at the very end: an object holding them.
const r = '2025-04'.replace(/(?<y>[0-9]{4})-(?<m>[0-9]{2})/, (...a) => a.at(-1).m);
console.log(r); // '04'
(...a) collects every argument into an array, and a.at(-1) is the last one, the groups object. Counting from the end is a good habit, because the number of arguments changes when the pattern gains a group.
Step 5: number the matches
The function can remember things between calls. Here a counter goes up each time:
const numberEach = (text) => {
let i = 0;
return text.replace(/a/g, () => String(++i));
};
console.log(numberEach('a a a')); // '1 2 3'
++i adds one to i and gives the new value. No replacement string could count like this.
Step 6: nothing is interpreted
In a replacement string, $& means "the match". In a function's return value it means nothing special:
console.log('x'.replace(/x/, () => '$&')); // '$&'
console.log('x'.replace(/x/, () => 42)); // '42'
What you return is used exactly as it is, and a number is turned into text for you. So when you insert data you didn't write, such as user input or prices with $ signs, a function is the safe choice.
Step 7: g decides how often it runs
let once = 0;
'aaa'.replace(/a/, () => { once++; return 'b'; });
let each = 0;
'aaa'.replace(/a/g, () => { each++; return 'b'; });
console.log(once, each); // 1 3
Without g the function runs for the first match only. With g it runs once per match.
The full solution
Here is the complete answer: bump, shoutWords, numberEach and checks for each argument the function receives. Press Run to see the three results.
const bump = (text) => text.replace(/[0-9]+/g, (d) => String(Number(d) + 1));
const shoutWords = (text) => text.replace(/[a-z]+/g, (w) => w.toUpperCase());
// A counter is easy this way, and impossible with a replacement string.
const numberEach = (text) => {
let i = 0;
return text.replace(/a/g, () => String(++i));
};
console.log('bump :', bump('room 9 and room 10'));
console.log('shoutWords :', shoutWords('a bc'));
console.log('numberEach :', numberEach('a a a'));
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('the function receives each match', shoutWords('a bc'), 'A BC');
test('and can compute the replacement', bump('room 9 and room 10'), 'room 10 and room 11');
test('the arguments are match, groups, offset', 'ab'.replace(/(a)(b)/, (m, g1, g2, offset) => [m, g1, g2, offset].join('|')), 'ab|a|b|0');
test('and then the whole input string', 'ab'.replace(/b/, (...args) => String(args.at(-1))), 'aab');
test('named groups arrive as one final object', '2025-04'.replace(/(?<y>[0-9]{4})-(?<m>[0-9]{2})/, (...a) => a.at(-1).m), '04');
test('a counter can number the matches', numberEach('a a a'), '1 2 3');
test('nothing in the returned string is interpreted, so no $ escaping', 'x'.replace(/x/, () => '$&'), '$&');
test('a non-string return value is converted', 'x'.replace(/x/, () => 42), '42');
test('without g the function runs once', (() => { let n = 0; 'aaa'.replace(/a/, () => { n++; return 'b'; }); return n; })(), 1);
test('with g it runs once per match', (() => { let n = 0; 'aaa'.replace(/a/g, () => { n++; return 'b'; }); return n; })(), 3);
The function form is the one to reach for whenever the replacement depends on what was matched, and the "no $ escaping" assertion is the underrated reason: whatever you return is used verbatim. Inserting arbitrary data into text is therefore safer with a function than with a string.
Counting the arguments from the end with args.at(-1) is a practical habit, because the count changes with the number of capture groups and with whether any are named. Positional destructuring of that list breaks as soon as the pattern gains a group.
Common mistakes
- Forgetting the
gflag. The function then runs once, so only the first match changes. - Returning a number and then doing string work on it. The return value is converted for you, but
d + 1inside the function joins text ('91'). Convert withNumber(d)first. - Reading groups by position when the pattern changes. Adding a group shifts the offset argument. Use named groups and
args.at(-1).
Try it yourself
- Double every number in
'2 apples and 5 pears'. - Capitalize the first letter of every word in
'hello big world'. - Replace each
?in'? and ?'with values from the array['tea', 'bread'], in order.