i want to make a program which count all the words in the string

  Kiến thức lập trình

Here i am trying to create a program which counts all the words that are there in a string, but it’s giving me an incorrect answer. Please have a look at this:

let text = "Hello world  ";
const mystring = text.split(" "); // output = "Hello", "world", " ", " "

console.log(mystring);

var countwords = 0

mystring.forEach((element) => {
    if(element != " "){
        countwords = countwords + 1
    }
    
})

console.log(countwords);

I was trying to create a program in js which would count all the words that are there in the string, but it’s giving me incorrect answer. Shouldn’t the output be 2, but instead of that it’s showing 4.

LEAVE A COMMENT