DEV Community

Discussion on: TIL: JavaScript replace() command with callback

Collapse
 
zeroxdg profile image
Nguyen Viet Hung • Edited

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.

Collapse
 
huytd profile image
Huy Tr.

Yeah, that's what I noticed after posted it here, to actually replace the nth match, we can write something like this:

const replaceNth = (input, search, replacement, nth) => {
    let occurrence = 0;
    return input.replace(search, matched => {
        occurrence++;
        if (occurrence === nth) return replacement;
        return matched;
    });
};