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 −

Example

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;
      if(!map.has(val)){
         map.set(val, 1);
         if(num === 0){
            res += char;
         }else{
            res += val;
         }
      }else{
         const freq = map.get(val);
         if(num - freq === 1){
            res += char;
         }else{
            res += val;
         };
         map.set(val, freq+1);
      };
      return { res, map };
   }, {
      res: '',
      map: new Map()
   });
   return creds.res;
}
console.log(replaceNthAppearance(str, num, char));

Output

The output in the console will be −

This ***a s*mple string
raja
Updated on 19-Oct-2020 10:12:19

Advertisements