1

So basically this is the instructions.

Write a program that will prompt the user for a sentence and for a word. The program should check whether the word exists in the sentence and let the user know whether or not it does. Now see if you can modify your program to count how many times the word appears in the sentence and then inform the user of the total count.

So far, so good until the next part. I cannot seem to find a way to count how many times a word appear in the sentence. More specifically this part Now see if you can modify your program to count how many times the word appears in the sentence and then inform the user of the total count..

Would really appreciate if there is some loop that could help or a function. We've been studying JavaScript just for one month.

This is my code so far

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Lab 3.3</title>

    <script>
        "use strict";

        var sentence = prompt("Please enter a sentence");

        alert ("So this is your sentence?" + sentence);

        var word = prompt("Please enter a word");

        alert ("So this is your word?" + word);

        var sentenceArray = sentence.split;
        var wordArray = word.split;

        alert (sentence.includes(word))


    </script>
</head>
<body>

</body>
Atara
  • 11
  • 4

1 Answers1

2

Create a regular expression from the word, with the flags i (case insensitive), and g (global - to find all occurrences).

Use String#Match with the expression to count the words:

var sentence = 'All cats are felines, but not all felines are cats. I cannot stress that more - not all felines are cats';
var word = 'not';
var pattern = new RegExp('\\b' + word + '\\b', 'ig');
var count = (sentence.match(pattern) || []).length;

console.log(count);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209