Your code is not completely correct. The index variable in the callback is actually the position of the match in the string. So if the task is still matching the 2nd occurrence in the string, your code will fail for this string: "abcabca" and the index for each match will be 0, 3, 8 and not 0, 1, 2. However, we can just add a variable to count the index of each occurrence so overall, nice discovery.
Fun fact: That index variable is also accessible in the regex itself using the lastIndex property.
Your code is not completely correct. The
index
variable in the callback is actually the position of the match in the string. So if the task is still matching the 2nd occurrence in the string, your code will fail for this string: "abcabca" and the index for each match will be0
,3
,8
and not0
,1
,2
. However, we can just add a variable to count the index of each occurrence so overall, nice discovery.Fun fact: That
index
variable is also accessible in the regex itself using the lastIndex property.Yeah, that's what I noticed after posted it here, to actually replace the nth match, we can write something like this: