JavaScript program to find most repeated word from a file or string


Following javascript program is to find the most repeated word in the given string and this is acheived by using for loop.

let str = 'How do you do?'; 
console.log(findMostRepeatedWord(str)); 

function findMostRepeatedWord(str) 
{ 
  let words = str.match(/\w+/g); // splitting words
  let occurances = {}; 
  for (let word of words) { 
    if (occurances[word]) { 
      occurances[word]++; 
    } 
    else { 
      occurances[word] = 1; 
    } 
  } 
  // Here occurances will give count of each word
  let max = 0; 
  let mostRepeatedWord = ''; 
  for (let word of words) { 
    if (occurances[word] > max) 
    { 
      max = occurances[word]; mostRepeatedWord = word; 
    } 
  } 
  return mostRepeatedWord; 
}

Output:

do

Try it Online here: https://onecompiler.com/javascript/3x737d62k