We can get the nth occurrence of a substring in a string with some JavaScript string methods.
For instance, we can write:
const string = "XYZ 123 ABC 456 ABC 789 ABC";
const getPosition = (string, subString, index) => {
return string.split(subString, index).join(subString).length;
}
console.log(
getPosition(string, 'ABC', 2)
)
We call split
with substring
and index
to split the string with substring
as the delimited and limit the number of splits to index
.
Then we join back the string with substring
with join
to join the string back together.
And then we get the length
of the joined string to get the index of the index
th occurrence of a string.
Therefore, the console log should log 16 since that’s the start of the 2nd occurrence of 'ABC'
.