const countWords = str => str.trim().split(/\s+/g).length;
Optimised code
const countWords = str => str.trim().split(/\s+/g).map(i => i.replace(/[\[\]?.,\/#!$%\^&\*;:{}=\"\-_~()…–—·'’]/g,"")).filter(i=>i).length;
Returns the number of words in a given string.
The repository & npm package
You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.
The code and the npm package will be updated every time I publish a new article.
Follow me on Twitter: @martinkr and consider to buy me a coffee
Photo by zoo_monkey on Unsplash
Top comments (5)
This would count
' - '
as a word. It would be better to use \W instead of \s.Hi Alex,
thank you for you contribution. You are right, a
-
surrounded by spaces would count as a word. Unfortunaltey,\W
breaks something like "foo-bar" also into two words.Based on you input I refined the code with a regular expression removing all punctuation chars from the results.
I would love I you have some feedback on this!
Thank you,
Martin
Non-word-characters only lead to errors if delimited by space on either side. So you can do
Thnx for this post! I like small useful code snippets like this!
Hi Dennis,
check out the oder articles in the series!
Cheers!