How to usea loop in Javascript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true
Example: Counting occurrence of for in “w3wiki” using Loops.
function gfg() {
let s = "Geeks for Geeks";
let f = "for";
let i = 0,
n = 0,
j = 0;
while (true) {
j = s.indexOf(f, j);
if (j >= 0) {
n++;
j++;
} else
break;
}
console.log(n);
}
gfg()
Output
1
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