How to find the index of Nth occurrence of a character in a string with Node.js

1 Answer

0 votes
function GetNthIndexOfCh(s, ch, n) {
    let count = 0;
    
    for (let i = 0; i <= s.length - 1; i++) {
        if (s[i] == ch) {
            count++;
            if (count == n) {
                return i;
            }
        }
    }
    
    return -1;
}

const str = "java c++ python node.js javascript";

console.log(GetNthIndexOfCh(str, 'a', 3));



/*
run:

25

*/

 



answered Mar 28, 2024 by avibootz
...