0

How can I show the frequency of every single word contained in a div or textarea? I found this thread that comes close to what I need, but I need to get the text from an element and not from the string

function getFrequency2(string, cutOff) {
  var cleanString = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,""),
      words = cleanString.split(' '),
      frequencies = {},
      word, frequency, i;

  for( i=0; i<words.length; i++ ) {
    word = words[i];
    frequencies[word] = frequencies[word] || 0;
    frequencies[word]++;
  }

  words = Object.keys( frequencies );

  return words.sort(function (a,b) { return frequencies[b] -frequencies[a];}).slice(0,cutOff).toString();
}

document.write( getFrequency2( "1 2 1 2 3 1 2 3 1 1 4 test", 3  ) ); 
Sim9b
  • 1
  • 2

2 Answers2

0

The text from an element is a string. So just send your function that, for example:

const myElementText = document.getElementById("elID").textContent; 
getFrequency2(myElementText, cutOff);
George
  • 2,330
  • 3
  • 15
  • 36
dikuw
  • 1,134
  • 13
  • 22
0

The question as I read it was how to send the text from an element to a given function. If the function doesn't work as expected, we'll need to know what your expected output is. For example, if you want to return an object with each word and the number of instances in the given string, you could do (with ES6):

<div id="elID">This is is a a a test test test test</div>

const myElementText = document.getElementById("elID").textContent; 
let counter = str => {
  return str.split(' ').reduce((total, word) => {
    total[word] ? total[word]++ : total[word] = 1;
    return total;
  }, {});
};
console.log(counter(myElementText));

This gives the output {This: 1, is: 2, a: 3, test: 4}

Working fiddle: https://jsfiddle.net/f46qzskd/

dikuw
  • 1,134
  • 13
  • 22