If you want to catch 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
takes word letters (ie anything other than space, punctuation, line break, apostrophe, etc.). The +
completes the expression so that each match is a sequence of one or more characters.
Warning: \w
does not take accented characters. If you need to have accented characters, you'll need a more complex regular expression. See this question , 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 key of the object. If it is not, it creates the key with a value of one. If it is already, it increases. 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 quantity of each word, just read the keys of the object:
for (let chave in mapa) {
console.log(mapa[chave]); // exemplo ilustrativo
}
Now just integrate everything into your code. Have fun!