sajad torkamani

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+), then p1 is the match for the 1st capture group (\w+) and p2 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 be undefined.
  • offset: The offset of the matched substring within the whole string. For example, if the string was abcde and the matched substring was de, the offset would be 3.
  • 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 the pattern contains at least one named capturing group.

Sources/links

Tagged: JavaScript