Using String.replace with a regex pattern and a replacement function
21 April 2024 (Updated 18 May 2025)
The String.replace() method can take a regular expression as its first argument and a function as its second argument. This enables powerful string replacement capabilities.
The syntax is:
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
return replacement;
}
The arguments are:
match: The matched substring.p1, p2, …, pN: The nth string found by the capture group. For example, if the pattern is/(\w+)(\d+), thenp1is the match for the 1st capture group(\w+)andp2is the match for the second capture group(\d+). If the group is part of a disjunction (e.g.'abc'.replace(/(f)|(c)/, replacer)), the unmatched alternative will beundefined.offset: The offset of the matched substring within the whole string. For example, if the string wasabcdeand the matched substring wasde, the offset would be3.string: The whole string being examined.- groups: An object whose keys are the used group names, and whose values are the matched portions (
undefinedif not matched). Only defined if thepatterncontains at least one named capturing group.
Sources/links
Tagged:
JavaScript recipes