Replacing every nth instance of characters in a string - JavaScript

We are required to write a JavaScript function that takes in a string as the first argument, a number, say n, as the second argument and a character, say c, as the third argument. The function should replace the nth appearance of any character with the character provided as the third argument and return the new string.


Following is the code −

const str = 'This is a sample string';
const num = 2;
const char = '*';
const replaceNthAppearance = (str, num, char) => {
   const creds = str.split('').reduce((acc, val, ind, arr) => {
      let { res, map } = acc;
         map.set(val, 1);
         if(num === 0){
            res += char;
            res += val;
         const freq = map.get(val);
         if(num - freq === 1){
            res += char;
            res += val;
      map.set(val, freq+1);
   return { res, map };
   }, {
      res: '',
      map: new Map()
   return creds.res;
console.log(replaceNthAppearance(str, num, char));


Following is the output in the console −

This ***a s*mple string

Updated on: 16-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started