Medium
Find the Most Frequent Word in a Sentence
Description
Building on the concept of counting occurrences, your task is to write a function that takes a string (sentence) as input and returns the most frequently occurring word in the sentence.
If multiple words have the same frequency, return the one that appears first.
This problem is useful in various real-world applications, such as:
- Analyzing word frequency in text documents.
- Optimizing search engines by identifying common keywords.
- Processing user input to understand popular terms.
Requirements
Input: A string containing words separated by spaces. The string may include punctuation, which should be ignored.
Output: The word that appears most frequently in the sentence. If there is a tie, return the word that appears first.
Considerations
- The function should be case-insensitive (e.g., "Tech" and "tech" are considered the same).
- Ignore punctuation such as .,!?;:
- Handle edge cases like an empty string or strings with only spaces.
Example Usage
mostFrequentWord("The quick brown fox jumps over the lazy dog.");// Expected output: "the"mostFrequentWord("Hello hello world!");// Expected output: "hello"mostFrequentWord("Coding is fun, and coding is life.");// Expected output: "coding"
Did you know?
JavaScript was originally called "LiveScript" before being renamed to JavaScript.
Test Cases
Input:
"Hello hello world!"
Expected Output:
"hello"