Function that only replaces character from string after specified appearances in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Therefore, let’s write the code for this function −


The code for this will be −

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


The output in the console will be −

This ***a s*mple string
Published on 19-Oct-2020 10:11:30