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