Count the number of occurrences of a given substring in a string

Count the number of occurrences of a given substring in a string

function COUNT_SUBSTR(str,sbStr){

 let count = 0;

 let pos = str.indexOf(sbStr);

 while (pos !== -1){

   count++;

   pos = str.indexOf(sbStr,pos+1);

 }

 return count;

}


The provided code defines a function called COUNT_SUBSTR that takes two parameters: str and sbStr. The purpose of this function is to count the number of occurrences of a substring (sbStr) within a given string (str).

Here is a detailed explanation of how the function works:

  1. let count = 0; creates a variable called count and initializes it to 0. This variable will be used to keep track of the number of occurrences of sbStr in str.
  2. let pos = str.indexOf(sbStr); initializes a variable called pos with the index of the first occurrence of sbStr in str. The indexOf() method returns the index of the first occurrence of the specified substring or -1 if it is not found.
  3. The while loop is used to iterate over str and find all occurrences of sbStr. It continues as long as pos is not equal to -1, which means that there are still more occurrences of sbStr to be found.
  4. Inside the while loop, count++ increments the count variable by 1, indicating that another occurrence of sbStr has been found.
  5. pos = str.indexOf(sbStr, pos + 1); updates the value of pos to the index of the next occurrence of sbStr in str, starting from the position immediately after the previous occurrence. This ensures that the loop continues to find all occurrences of sbStr and doesn’t get stuck in an infinite loop.
  6. Once there are no more occurrences of sbStr in str, the indexOf() method returns -1, causing the while loop to exit.
  7. Finally, the function returns the value of count, which represents the total number of occurrences of sbStr in str.

In summary, this function uses a loop and the indexOf() method to iterate over a string and count the number of occurrences of a specific substring within it.

strsubstroutput
hello worldl3
bananaa3
mississippiss2
javascriptscript1
applebanana0