Using String.replace with a regex pattern and a replacement function
21 April 2024 (Updated 21 April 2024)
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+)
, thenp1
is the match for the 1st capture group(\w+)
andp2
is 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 wasabcde
and 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 (
undefined
if not matched). Only defined if thepattern
contains at least one named capturing group.
Sources/links
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment