Open In App

How to get nth occurrence of a string in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, the task is to get the nth occurrence of a substring in a string with the help of JavaScript. We have many methods to do this some of which are described below:

Approaches to get the nth occurrence of a string:

Approach 1: Using split() and join() methods

  • First, split the string into sub-strings using the split() method by passing the index also.
  • Again join the substrings on the passed substring using join() method.
  • Returns the index of the nth occurrence of the string.

Example: In this example, the split() and join() methods are used to get the index of a substring. 

Javascript




// Input string
let string = "Geeks gfg Geeks Geek Geeks gfg";
 
// String to search
let searchString = "Geeks";
 
// occurrence number
let occurrence = 3;
console.log(
    occurrence +
        "rd occurrence of a '" +
        searchString +
        "' in " +
        string +
        "'."
);
 
// Function to get index of occurrence
function getPos(str, subStr, i) {
    return str.split(subStr, i).join(subStr).length;
}
 
function GFG_Fun() {
    console.log(getPos(
        string,
        searchString,
        occurrence
    ));
}
 
GFG_Fun();


Output

3rd occurrence of a 'Geeks' in Geeks gfg Geeks Geek Geeks gfg'.
21

Approach 2: Using indexOf() method

Go through each substring one by one and return the index of the last substring. This approach uses the indexOf() method to return the index of the nth occurrence of the string. 

Example: This example uses the indexOf() method to find the index of a substring.

Javascript




// Input string
let string = "Geeks gfg Geeks Geek Geeks gfg";
 
// String to search
let searchString = "Geeks";
 
// occurrence number
let occurrence = 3;
console.log(
    occurrence +
        "rd occurrence of a '" +
        searchString +
        "' in " +
        string +
        "'."
);
 
// Function to get index of occurrence
function getIndex(str, substr, ind) {
    let Len = str.length,
        i = -1;
    while (ind-- && i++ < Len) {
        i = str.indexOf(substr, i);
        if (i < 0) break;
    }
    return i;
}
 
function GFG_Fun() {
    console.log(getIndex(string, searchString, occurrence));
}
 
GFG_Fun();


Output

3rd occurrence of a 'Geeks' in Geeks gfg Geeks Geek Geeks gfg'.
21



Last Updated : 19 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads