How to get nth occurrence of a string in JavaScript ?
Last Updated :
19 Jul, 2023
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
let string = "Geeks gfg Geeks Geek Geeks gfg" ;
let searchString = "Geeks" ;
let occurrence = 3;
console.log(
occurrence +
"rd occurrence of a '" +
searchString +
"' in " +
string +
"'."
);
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
let string = "Geeks gfg Geeks Geek Geeks gfg" ;
let searchString = "Geeks" ;
let occurrence = 3;
console.log(
occurrence +
"rd occurrence of a '" +
searchString +
"' in " +
string +
"'."
);
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
Share your thoughts in the comments
Please Login to comment...