So ive written a code which would detect all the words that are there in a sentence. I would only detect the words and would ignore the spaces, which means even if there are empty spaces in the string i would not count them. But the result are not what i expected. Here is the code :
var mystring = "Hello World"
var indexcount = 0
var words = 0
for (element of mystring) {
if (element == " " || element[indexcount + 1] != " " || element[indexcount - 1] != " ") {
var words = words + 1
var indexcount = indexcount + 1
} else {
indexcount = indexcount + 1
}
}
console.log(words);
So this code would actually help anyone who would want to know all the words that are there in a string, ignoring all the spaces. So even if you had just a single word within a string and a lot of spaces still, the result would be 1. But i am getting weird ouputs. please help
3
Answers
Here is the Solution that you can try
Try using this function:
You have several errors:
var
after the first use on a variablea. a first element in a string (indexcount === 0)
b. or the previous character is a space (mystring[index – 1] === ‘ ‘)
If so increase the word count
Consider using a state machine:
You could also use a regex: