Picking positions of a word within a text

1

I have text and want to get the initial positions of a specific word in all occurrences within that text. For example, I have the following text:

maria gosta de joão. jose gosta de maria. maria gosta de joao e jose.

Note that the word " maria " has 3 occurrences. If I used indexOf("maria") , the result would be 0 , because indexOf takes only the first occurrence. Only indexOf does not take the position of all occurrences, only the first and last with lastIndexOf .

What I wanted was to get the position of the 3 words "Maria", which in the text above would be:

maria gosta de joão. jose gosta de maria. maria gosta de joao e jose.
↑                                  ↑      ↑
0                                  35     42

I could do this by scrolling through the text, character by character, but if the text is too long, I do not see it that way.

What efficient technique or better could I use to achieve this result? Maybe a regex?

    
asked by anonymous 16.02.2018 / 19:20

1 answer

4

A simple way to construct the result you want is to use the second parameter of indexOf that allows you to indicate where you are looking.

From documentation :

  

arr.indexOf (searchElement [ fromIndex])

So it initially starts from 0 , and on subsequent calls it starts where it had previously ended, ending with -1 which is when it does not have any more.

Example:

let texto = "maria gosta de joão. jose gosta de maria. maria gosta de joao e jose.",
    procura = "maria",
    posicoes = [],
    posicaoCorrente = texto.indexOf(procura);

while (posicaoCorrente != -1) {
  posicoes.push(posicaoCorrente);
  posicaoCorrente = texto.indexOf(procura, posicaoCorrente + procura.length);
}

console.log(posicoes);
    
16.02.2018 / 19:36