Create a polyfill to replace nth occurrence of a string JavaScript

Let’s say, we have created a polyfill function removeStr() that takes in three arguments, namely −

  • subStr → the occurrence of which String is to be removed

  • num → it’s a Number (num)th occurrence of subStr is to be removed from string

The function should return the new if the removal of the subStr from the string was successfully, otherwise it should return -1 in all cases.

For example −

const str = 'drsfgdrrtdr';
console.log(str.removeStr('dr', 3));

Expected output −


Let’s write the code for this −


const str = 'drsfgdrrtdr';
const subStr = 'dr';
const num = 2;
removeStr = function(subStr, num){
      return -1;
   let start = 0, end = subStr.length;
   let occurences = 0;
   for(; ;end < this.length){
      if(this.substring(start, end) === subStr){
      if(occurences === num){
         return this.substring(0, start) + this.substring(end,
   return -1;
String.prototype.removeStr = removeStr;
console.log(str.removeStr(subStr, num));


Output for this code in the console will be −


Understanding the code −

  • The removeStr() function firstly checks if there’s not even a single occurrence of subStr then we should exit out and return -1.

  • Then it uses the sliding window algorithm to record the number of occurrences of subStr in string(the size of window being equal to length of subStr).

  • Initially we start from leftmost window then we keep sliding our window till the end of window reaches the end of original string.

  • If in our way, the count of occurrences equals the required occurrence, we trim that occurrence from the string and return the new string thus obtained.

  • If we iterate through the whole string, it means that there are not enough occurrences of subStr in string and in which case we should return -1 and exit the function

Lastly, we add the removeStr property to String.prototype so that we can call it as a string function.

Updated on: 19-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started