Word count
Word count
Hi there.
I'm trying to do a word count and obviously I'm not the first but I haven't found a way to do it without just counting the spaces.
I guess if you have a text like:
"Let me count the words for you."
there will be 6 spaces so I could just count the spaces via
words = stripped.split(" ").length;
and add 1 and I would have the number of the words: 7
But if someone mistakenly enters:
"Let me count _______ the words for you." (_ representing additional whitespace)
I wouldn't get 7...I would get a thousand (approximately).
So I tried with the replace function and some regular expressions I do not understand at all.
text.replace(/\s+/g, " ");
Basically my question is. What is the right regex to trim the text so I get rid of leading and trailing spaces AND convert multiple spaces in the middle of the text to only one space:
" Let me count ________ the words for you. "
to
"Let me count the words for you."
???