skip to Main Content

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.

6

Answers


  1. You can use a regex to check for empty strings. Here in your splitted array you don’t have " " (space) but "" (empty string) after the two words.
    Check here :How to check if a variable is null or empty string or all whitespace in JavaScript?

    You can replace your condition element != "" with a call to this function :

    function isEmptyOrSpaces(str){
      return str === null || str.match(/^ *$/) !== null;
    }
    

    Also instead of counting afterwards, you can use a filter function to filter the empty strings of the array, and then get the array.length to get the word count:

    const countwords  = mystring.filter(isEmptyOrSpaces).length
    
    Login or Signup to reply.
  2. The problem that an empty string isnt a space:

    element != " " // this is true for empty strings too
    

    To fix:

    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);
    Login or Signup to reply.
  3. That’s maybe because you have split those words in the array by a space. I tried it myself, I saw the output and the last two strings didn’t have anything in them. As per your if statement, it would only add one to countwords IF the string is not having space. But those last two strings didn’t have space, so it fulfills the condition and adds one to countwords. Hope this helps you 🙂

    Login or Signup to reply.
  4. So there is a prototype.trim() in javascript what it does it trims off the whitespaces around the string but points to be noted it doesn’t removes the whitespaces in the middle of the string so it won’t be beneficial at that particular moment.
    Below is the suggested code which solves the problem and always try to use return statement if you are into competitive/problem solving programming.

    let text = "Hello World  ";
    const myString = text.trim().split(' ');
    
    const splitText = (str) => {
        let countwords = 0;
        str.forEach((element) => {
            if(element != " ") {
                countwords +=  1;
            }
        })
        return countwords;
    }
    splitText(myString);
    

    Or You can also do like your style:

    let text = "Hello World  "
    let countwords = 0
    
    const myString = text.trim().split(' ');
    
    myString.forEach((element) => {
        if(element != " ") {
            countwords +=  1
        } 
    })
    
    console.log(countwords);
    
    Login or Signup to reply.
  5. The issue here is that splitting the string "Hello world " using .split(" ") creates an array with extra empty strings ("") because of the extra spaces in the input string. To fix this, you can use .filter() to remove the empty strings from the array before counting the words. Here’s the corrected version of your code

    let text = "Hello world  ";
    const mystring = text.split(" ").filter(word => word !== ""); 
    
    console.log(mystring);
    
    var countwords = 0
    
    mystring.forEach((element) => {
        if(element != " "){
            countwords = countwords + 1
        }
    })
    
    console.log(countwords);

    This code should give you the correct output of 2.

    But best way is:

    let text = "Hello world  ";
    const countWords = text.trim().split(/s+/).length;
    
    console.log(countWords);
    Login or Signup to reply.
  6. This is how I would do it:

    const text = "Hello world  , . ";
    const filter = (str) => Boolean(str) && /[a-z]/gi.test(str);
    const result = text.split(' ').filter(filter).length;
    console.log(result); // 2
    

    Firstly, I divide the string in multiple strings by splitting it where spaces are found.

    Then, the filter function returns true only if the string provided is not empty and is a word (so it’s made of letters).

    This way, every unwanted character or empty strings are not counted.

    Also you can change the regex (/[a-z]/gi) to accept any other characters you want.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search