Post

Find the nth occurrence of a string (JavaScript)

I was playing around in JavScript needing to find 7’th position of a ( within a long string. Messing about with the indexOf and substring methods were a bit too cumbersome so I came up with the following code snippet. Hopefully this saves you some time.

1
2
3
4
5
6
7
8
9
function nthOccurrence(str, s, c) {
    var strlen = str.length;
    var matches = 0;

    for(i = 0; i < strlen; i++){
        if(str[i] === s) matches++;
        if(matches == c) return i;
    }
}
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.