Sometimes, we want to count words in string with JavaScript.
In this article, we’ll look at how to count words in string with JavaScript.
How to count words in string with JavaScript?
To count words in string with JavaScript, we can use the string split method.
For instance, we write
const numWords = string.split(/\s+/).length;
to call string.split with the /\s+/ regex to split the string string by the spaces.
It returns an array with the split strings.
So we get the number of words in the string with the length property.
Conclusion
To count words in string with JavaScript, we can use the string split method.