Open In App
Related Articles

How to get nth occurrence of a string in JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Jul, 2023
Like Article
Save Article
Similar Reads
Related Tutorials