Good idea! However, there is an issue with this approach. If you input a string with special characters, like this: "Hello - world", it would count it as 3 words instead of 2. Your code registers anything between two whitespace characters as a word. To solve that problem, we can use regex.
\w is used for matching word characters - it matches a letter, a number or an underscore. To match the whole word, we simply write \w+
Good idea! However, there is an issue with this approach. If you input a string with special characters, like this: "Hello - world", it would count it as 3 words instead of 2. Your code registers anything between two whitespace characters as a word. To solve that problem, we can use regex.
\w
is used for matching word characters - it matches a letter, a number or an underscore. To match the whole word, we simply write\w+
So instead of
We could write
If we want to match alphabetical characters only, we can use
[a-zA-Z]
instead of\w
, or we can play around with the regex based on our needs.Bonus: you can use
map
andreduce
to make this code shorter:Hope this helps!
It helps Damnjan, thanks! I still need to count characters and spaces tho maybe using
match(/\s/g)
will do with total length.