w3resource

JavaScript: Find the most frequent word in a string

JavaScript String: Exercise-59 with Solution

Write a JavaScript program to find the most frequent word in a given string.
Test Data:
("The quick brown fox jumps over the lazy dog") -> "the"
("Python is a high-level, general-purpose programming language.") -> "python"
(" It was the same man, she was sure of it. It's always the same, Chauncey.") -> "was"
(12321) -> "It must be a string."

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to find the most frequent word in a string</title>
</head>
<body>

</body>
</html>

JavaScript Code:

const test = (text) => { 
   if (text.length === 0) 
    {
    return 'String should not be empty!'
   }
    if (typeof text !== 'string')
     {
       return 'It must be a string.'
     }
   const data = text.split(' ')
  if (data.length < 2) {
    return data[0]
  }
   const words = text.split(' ')
  if (words.length < 2) {
    return words[0]
  }
  const temp = {}
  words.forEach(word => {
    temp[word.toLocaleLowerCase()] = temp[word.toLocaleLowerCase()] + 1 || 1
  })
  const max = Object.keys(temp).reduce((n, word) => {
    if (temp[word] > n.count) 
    { 
      return { word, count: temp[word] } 
    } 
    else 
    { 
      return n 
    }
  }, { word: '', count: 0 })
  return max.word
}
console.log(test("The quick brown fox jumps over the lazy dog"))
console.log(test("Python is a high-level, general-purpose programming language."))
console.log(test(" It was the same man, she was sure of it. It's always the same, Chauncey."))
console.log(test(12321))

Sample Output:

the
python
was
It must be a string.

Flowchart:

Flowchart: JavaScript: find the most frequent word in a string

Live Demo:

See the Pen javascript-string-exercise-59 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Find the most frequent character in a string.
Next: Reverse words in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.