There are many approaches to count occurrences of a substring inside a string. In this post we will cover two approaches -
Methods
- Using loop
- Using Regular Expressions
Method 1 — Using Loop
We can use a loop to iterate through the string and count the number of occurrences of the substring.
Let’s try this out -
We used the indexOf() method to search for the first occurrence of the substring in the string.
If the indexOf() method finds an occurrence (i.e., it returns a non-negative value), increment the count variable and update currentIndex to the position just after the found occurrence.
Read more at: https://codeymaze.com/how-to-count-occurences-in-a-string-in-javascript/
Originally published at https://codeymaze.com on September 9, 2023.