DEV Community

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

Posted on • Updated on

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


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!