loading...

re: TIL: JavaScript replace() command with callback VIEW POST

TOP OF THREAD FULL DISCUSSION
re: 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 stil...
 

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;
    });
};
code of conduct - report abuse