DEV Community

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

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;
    });
};