DEV Community

Discussion on: How to make a word counter with JavaScript🦸‍♂️

Collapse
 
phata83 profile image
MOUHAMADOU Sow

Hello this is great your word counter but the only problem is that it counts spaces as words.
Let's take the following sentence as an example:
"This is a word counter"
This sentence has 6 words but it will put 12 words because there are extra spaces.
How can we fix this?

Collapse
 
mellen profile image
Matt Ellen

I haven't tried the full code, but from what I can see it specifically doesn't count spaces.

The part of the code that does the counting:

let totalWord = text.split(' ').length;
Enter fullscreen mode Exit fullscreen mode

If you replace text with 'This is a word counter' then you get the correct answer of 5.