Sometimes, we to find the nth occurrence of a character in a string in JavaScript.
In this article, we’ll look at how to find the nth occurrence of a character in a string in JavaScript.
How to find the nth occurrence of a character in a string in JavaScript?
To find the nth occurrence of a character in a string in JavaScript, we can use the string indexOf
method with the from index argument.
For instance, we write:
const indexOfNth = (string, char, nth, fromIndex = 0) => {
const indexChar = string.indexOf(char, fromIndex);
if (indexChar === -1) {
return -1;
} else if (nth === 1) {
return indexChar;
} else {
return indexOfNth(string, char, nth - 1, indexChar + 1);
}
}
const str = 'foobarfoobaz'
console.log(indexOfNth(str, 'o', 3))
We define the indexOfNth
function that recursively calls string.indexOf
with fromIndex
as the 2nd argument to start searching from fromIndex
.
If indexOf
returns -1, we return -1 since char
isn’t in string
.
If indexOf
returns 1, then we found the index of the nth occurrence so we return indexChar
.
Otherwise, we keep searching by calling indexOfNth
with nth - 1
and indexChar + 1
.
Therefore, 7 is logged from the console log since the 3rd o is at index 7.
Conclusion
To find the nth occurrence of a character in a string in JavaScript, we can use the string indexOf
method with the from index argument.