The Wayback Machine - https://web.archive.org/web/20230715235043/https://www.geeksforgeeks.org/how-to-count-string-occurrence-in-string-using-javascript/
Skip to content
Related Articles
Open In App

Related Articles

How to count string occurrence in string using JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array. By counting the array size which will return the number of times the sub-string is present in a string. Script to find the number of occurrences in a string:

Example 1: Counting occurrence of Geeks in “GeeksforGeeks” using the “match()” function. 

Javascript




function gfg() {
    let r = "Geeks For Geeks ";
    console.log(
        (r.match(/Geeks/g)).length);
 
}
gfg()

Output

2

The ‘g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence.

Example 2: Counting occurrence of for in “GeeksforGeeks” using Loops. 

Javascript




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

Example 3: Counting occurrence of Geeks in “GeeksforGeeks” using split() function. 

Javascript




function gfg() {
    let s = "Geeks for Geeks";
    let f = "Geeks";
    let r = s.split(f).length - 1;
    console.log(r);
}
gfg()

Output

2

Example 4: Counting occurrence of Geeks in “GeeksforGeeks” using indexof(). 

Javascript




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

Last Updated : 14 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials