In the function replace
, you have the option to pass a function as a parameter. This function will receive specific arguments:
The arguments passed to the function are:
match, submatch1, submatch2, ..., offset, string
where
match
represents the entire matched string
submatch1, submatch2, ...
correspond to the strings that match the capturing groups in the regex pattern
offset
denotes the starting position of the matching string within the input string
string
is the complete string being analyzed
The number of arguments received by the function depends on the number of capturing groups in the regular expression.
In the provided example, there is one capturing group, so the function can accept up to 4 arguments.
myString = "a&b;c a&&c;; ab;&;c";
myString = myString.replace(/&([^&;]+);/g,
function(param0,param1,param2,param3) {
document.write("param0 = " + param0 + " (match)<br>");
document.write("param1 = " + param1 + " (first submatch)<br>");
document.write("param2 = " + param2 + " (offset)<br>");
document.write("param3 = " + param3 + " (whole string)<br>");
document.write("<br>");
return "[" + param0 + "]";
}
);
document.write(myString);