i'm new to javascript langguage and still learning some of the data types and i get execise which i can not comprehend, please help me.
The exercise question :
'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence.
so i tried some of the basic method such as,
and i cannot count the words love and given love words index.
how can i code this to find the answers?
This should work.
let sentence = "Love is the best thing in this world.
Some found their love and some are still looking for their love."
console.log(sentence.split("love").length)
This should work
const sentence = 'Love is the best thing in this world. Some found their love and some are still looking for their love.'
const occurrences = sentence.match(/love/gi); // (g is is for match all occurrences, i is for case insensitive)
console.log("number of occurrences of 'love'", occurrences.length)
To make it a little more generic and to show of the use of reduce:
const data = "Love is the best thing in this world. Some found their love and some are still looking for their love"
const dataArray = data.split(' ');
const wordMap = dataArray.reduce((result, word) => {
result[word.toLowerCase() ]= result[word.toLowerCase() ] ? result[word] + 1 : 1;
return result
}, {});
console.log(wordMap["love"])
console.log(wordMap["is"])
console.log(wordMap["best"])