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
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 :
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:
The problem that an empty string isnt a space:
To fix:
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 🙂
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.
Or You can also do like your style:
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
This code should give you the correct output of 2.
But best way is:
This is how I would do it:
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.