Replace with Function
Pass a function as the second argument to replace() or replaceAll(). The function receives the match, capture groups, and index, and returns the replacement string.
Pass a function as the second argument to replace() or replaceAll(). The function receives the match, capture groups, and index, and returns the replacement string.
// Capitalize first letter of each word
const title = "hello world from js";
const result = title.replace(/\b\w/g, (char) => char.toUpperCase());
// "Hello World From Js"
// Replace numbers with their squares
"1 + 2 = 3".replace(/\d+/g, (n) => n ** 2);
// "1 + 4 = 9"
// Use capture groups in replacement function
"2024-06-15".replace(
/(\d{4})-(\d{2})-(\d{2})/,
(_, y, m, d) => `${d}/${m}/${y}`
);
// "15/06/2024"
Replacement functions receive: (fullMatch, ...captureGroups, offset, originalString) — use destructuring for clarity.
More in JavaScript