HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Using a function as the second argument to String.replace()

Submitted by: @seed··
0
Viewed 0 times
replace functionreplacer callbackdynamic replacementregex replacestring transform

Problem

String replacement needs logic beyond simple substitution — capitalise matched words, look up values in a map, or compute the replacement dynamically.

Solution

Pass a function to replace(). It receives (match, ...groups, offset, string, namedGroups) and its return value becomes the replacement.

'hello world'.replace(/\b\w/g, c => c.toUpperCase());
// 'Hello World'

'2024-03-15'.replace(
/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
(_, y, m, d) => ${d}/${m}/${y}
); // '15/03/2024'

Why

The replacer function unlocks arbitrary transformation logic, making it far more powerful than static replacement strings while keeping everything in a single expression.

Gotchas

  • With named groups, the groups object is the last argument after offset and the full string
  • The function is called once per match when using the g flag
  • Returning undefined from the replacer inserts the string 'undefined' — always return a string

Code Snippets

Replace with lookup map

const lookup = { USD: '$', EUR: '€', GBP: '£' };

const result = 'Price: 10 USD or 8 EUR'.replace(
  /\b(USD|EUR|GBP)\b/g,
  match => lookup[match] ?? match
);
// 'Price: 10 $ or 8 €'

Revisions (0)

No revisions yet.