How to usesplit() and join() methods in Javascript

  • 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

How to get nth occurrence of a string in JavaScript ?

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:

Similar Reads

Approaches to get the nth occurrence of a string:

Table of Content Approach 1: Using split() and join() methodsApproach 2: Using indexOf() methodApproach 3: Using regular expressions...

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....

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....

Approach 3: Using regular expressions

Regular expressions offer a powerful way to search for patterns within strings. We can leverage the exec() method along with a regular expression to find the nth occurrence of a substring....