How to useIndexof() in Javascript
indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
Example: Counting occurrence of Geeks in “w3wiki” using indexof().
function gfg() {
let s = "Geeks for Geeks";
let f = "Geeks";
let r = s.indexOf(f);
let c = 0;
while (r != -1) {
c++;
r = s.indexOf(f, r + 1);
}
console.log(c);
}
gfg()
Output
2
How to count string occurrence in string using JavaScript ?
In JavaScript, we can count the string occurrence in a string by counting the number of times the string is present in the string.
This can be done in the following ways:
Table of Content
- Approach 1: Using match() function
- Approach 2: Using a loop
- Approach 3: Using split() function
- Approach 4: Using Indexof()
- Approach 5: Using regular expressions