javascriptstringindexoflastindexof

Javascript - Find position of specific occurrence of a word in a string (not first or last)


if I have a string which has a lot of times the same word, lets say:

"new question, new topic, new query, new code, new language, new answer"

Here we have the word "new" 6 times, but i want to find the position of the 4th "new".

I know IndexOf returns the position of the first occurrence and LastIndexOf returns the last one, but how can I find the position of the 4th occurrence???

Thanks!


Solution

  • You could use the second parameter fromIndex of String#indexOf and take the previously found position for starting a new seach.

    var string = "new question, new topic, new query, new code, new language, new answer",
        i = 0,
        pos = -1
        
    do {
        pos = string.indexOf('new', pos + 1);
        i++;
    } while (pos !== -1 && i < 4)
    
    console.log(pos);