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


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

Updated on: 09-Oct-2020

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements