2

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!

edwin26
  • 23
  • 2
  • 3
    Duplicate of this question, please see here: https://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string – Nick Oct 11 '17 at 21:18
  • Possible duplicate of [How to get the nth occurrence in a string?](https://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string) – Unamata Sanatarai Oct 11 '17 at 21:19

2 Answers2

0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can do

let str = "new question, new topic, new query, new code, new language, new answer"

let re = /new/g;
let myArray, count = 4;
while ((myArray = re.exec(str)) !== null && count--);
console.log(count==-1 && myArray.index);
marvel308
  • 10,288
  • 1
  • 21
  • 32