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


Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read 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!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs