Picking up positions of a word within a text

Asked

Viewed 342 times

0

I have a text and I want to pick up the starting 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 the indexOf takes only the first instance. 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 "mary", which in the above text 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 going through the text, character by character, but if the text is too long, I don’t see a good way.

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

  • you want to avoid the loop with substring?

  • I preferred because if the text is too large, it is half Abajara. You can even use a loop at some point, but wanted a more efficient way.

1 answer

5


An easy way to build the result you want is to use the second parameter of the indexOf which allows you to indicate from where you are searching.

Of documentation:

arr.indexof(searchElement[, fromIndex])

Thus initially begins from the 0, and subsequent calls begin where it had ended previously, ending with -1 which is when there’s no 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);

  • True. I forgot that the index has a second parameter. I have serious memory problem. Obg!

  • @dvd No problem, we are all here to help :). It is easy a detail of those go unnoticed.

  • @Isac, Boa, I didn’t even know I had this Overload and would post the answer breaking with substring as I had commented on the question.

  • @Leandroangelo Put your answer too. Every valid answer is welcome, no matter if it is the best (who knows?).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.