String function to replace nth occurrence of a character in a string JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a function removeStr() that lives on String.prototype object and takes in a string str, a character char and a number n.

The function should remove the nth appearance of char from str.

Let’s write the code for this −

const str = 'aaaaaa';
const subStr = 'a';
const num = 6;
removeStr = function(subStr, num){
   if(!this.includes(subStr)){
      return -1;
   }
   let start = 0, end = subStr.length;
   let occurences = 0;
   for(; ;end < this.length){
      if(this.substring(start, end) === subStr){
         occurences++;
      };
      if(occurences === num){
         return this.substring(0, start) + this.substring(end, this.length);
      };
      end++;
      start++;
   }
   return -1;
}
String.prototype.removeStr = removeStr;
console.log(str.removeStr(subStr, num));

Output for this code in the console will be −

aaaaa
raja
Published on 09-Oct-2020 15:15:47
Advertisements