DEV Community

Cover image for 1 line of code: How to count the words in a string
Martin Krause
Martin Krause

Posted on • Edited on

4 1

1 line of code: How to count the words in a string

const countWords = str => str.trim().split(/\s+/g).length;
Enter fullscreen mode Exit fullscreen mode

Optimised code

const countWords = str => str.trim().split(/\s+/g).map(i => i.replace(/[\[\]?.,\/#!$%\^&\*;:{}=\"\-_~()…–—·'’]/g,"")).filter(i=>i).length;
Enter fullscreen mode Exit fullscreen mode

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


Subscribe to the weekly modern frontend development newsletter


AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

This would count ' - ' as a word. It would be better to use \W instead of \s.

Collapse
 
martinkr profile image
Martin Krause

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

Collapse
 
lexlohr profile image
Alex Lohr

Non-word-characters only lead to errors if delimited by space on either side. So you can do

str.replace(/\s\W+\s/g, ' ').trim()...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dennisfrijlink profile image
Dennis Frijlink

Thnx for this post! I like small useful code snippets like this!

Collapse
 
martinkr profile image
Martin Krause

Hi Dennis,
check out the oder articles in the series!

Cheers!

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay