Answers for "Write a code that will print how many times a word is present in a particular string and also print the index of where it's found."

0

Write a code that will print how many times a word is present in a particular string and also print the index of where it's found.

const str = "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn't really happy.";
const pattern = /happy/g;
let count = 0;
while((result = pattern.exec(str)) !== null) {
 count++;
 console.log(result[0], pattern.lastIndex - result[0].length);
}

console.log("Total Occurrences:", count);

/* output
happy 7
happy 43
happy 82
happy 109
Total Occurrences: 4
*/
Posted by: Guest on October-17-2021

Code answers related to "Write a code that will print how many times a word is present in a particular string and also print the index of where it's found."

Browse Popular Code Answers by Language