Regular Expression for accurate word-count using JavaScript

This should do what you’re after:

value.match(/\S+/g).length;

Rather than splitting the string, you’re matching on any sequence of non-whitespace characters.

There’s the added bonus of being easily able to extract each word if needed 😉

Leave a Comment