DEV Community

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

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