If you want to pick up the words, you can use a regular expression. So:
let texto;
// preencha a variável acima da forma que achar melhor
let palavras = texto.match(/\w+/g);
Explanation: the regular expression \w
take letters of words (i.e.: anything that is not space, punctuation, line break, apostrophe, etc.). The +
complements the expression so that each match is a sequence of one or more characters.
Heed: \w
does not take accented characters. If you need to count accented characters, you will need a more complex regular expression. See this question about this, from which we can deduce two regular expressions:
/[a-záàâãéèêíïóôõöúçñ']+/gi
Or:
/[a-zA-Z\u00C0-\u00FF']+/gi
Next comes the coolest part. Every Javascript object is a hashmap. Then you create an empty object, and for each word you check if it is already the key of the object. If it is not, create the key with value one. If it is already, increase. So:
let mapa = {};
for (let i = 0; i < palavras.length; i++) {
let chave = palavras[i];
if (!mapa[chave]) {
mapa[chave] = 1;
} else {
mapa[chave]++;
}
}
At the end of this, to check the amount of each word, just read the object keys:
for (let chave in mapa) {
console.log(mapa[chave]); // exemplo ilustrativo
}
Now just integrate everything into your code. Have fun!
You want to count how many times a word appears within a given element, that’s it?
– Sergio