JavaScript - Writing a string function to replace the kth appearance of a character

Let’s say, we are required to write a String.prototype function that takes in three arguments.

  • First argument is string that should be searched for substrings
  • Second argument is the string, the occurrence of which String to be removed
  • Third argument is a Number say n, nth occurrence of substring to be removed from string.

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


Following is the code −

const str = 'jkdsttjkdsre';
const subStr = 'jk';
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,this.length);
String.prototype.removeStr = removeStr;
console.log(str.removeStr(subStr, num));

This 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 there are not enough occurrences of subStr in string and in that 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.


This will produce the following output in console −