Day 2 Exercise Level3 : why I have two most frequent words
Author: Yugio-TangCreated Jun 10, 2023Updated May 2, 2025
Hellow, Thank you for the work you've done. I don't know whether I am not sure whether I complete the task 3 in the level3 of the exercise which finding the most frequent word with given the sentence.
/*3.
Clean the following text and find the most frequent word :
(hint, use replace and regular expressions).
*/
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching';
// Regex of symbol
let symbolPattern = /\W/gi;
replacement = sentence.replace(/ /gi, 'SYMBOL');
replacement = replacement.replace(symbolPattern, '');
replacement = replacement.replace(/SYMBOL/gi, ' ');
console.log("task3. regex X replace: \n", replacement);
let words = replacement.split(' ');
let frequency = {};
let maxFrequency = 0;
let mostFrequentWord = '';
console.log(words);
for (let i=0; i < words.length; i++){
// case insensitive matching
//let word = words[i].toLowerCase();
let word = words[i];
if (frequency[word]){
frequency[word] += 1;
} else {
frequency[word] = 1;
}
if (frequency[word] > maxFrequency) {
mostFrequentWord = word;
maxFrequency = frequency[word];
}
}
console.log(frequency)
console.log(maxFrequency,mostFrequentWord );
output :
task3. regex X replace:
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher This 30DaysOfJavaScript is also the result of love of teaching
[
'I', 'am', 'a',
'teacher', 'and', 'I',
'love', 'teaching', 'There',
'is', 'nothing', 'as',
'more', 'rewarding', 'as',
'educating', 'and', 'empowering',
'people', 'I', 'found',
'teaching', 'more', 'interesting',
'than', 'any', 'other',
'jobs', 'Does', 'this',
'motivate', 'you', 'to',
'be', 'a', 'teacher',
'This', '30DaysOfJavaScript', 'is',
'also', 'the', 'result',
'of', 'love', 'of',
'teaching'
]
{
I: 3,
am: 1,
a: 2,
teacher: 2,
and: 2,
love: 2,
teaching: 3,
There: 1,
is: 2,
nothing: 1,
as: 2,
more: 2,
rewarding: 1,
educating: 1,
empowering: 1,
people: 1,
found: 1,
interesting: 1,
than: 1,
any: 1,
other: 1,
jobs: 1,
Does: 1,
this: 1,
motivate: 1,
you: 1,
to: 1,
be: 1,
This: 1,
'30DaysOfJavaScript': 1,
also: 1,
the: 1,
result: 1,
of: 2
}
3 I
It's a bit confusing with the result : the count of 'teaching' is also 3.
Source: Asabeneh/30-Days-Of-JavaScript