DEV Community

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

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