Count Number of Words in a String
To count number of words in a string in JavaScript, split the string with all white space characters as a delimiter, remove the empty splits (empty strings in the array), and count the number of items in resulting array. The count must represent the number of words in the given string.
The sample code to count number of words in a string str
is
var splits = str.split(/(\s+)/); var words = splits.filter((x) => x.trim().length>0); var count = words.length;
We can also use a single expression as shown in the following, using chaining.
str.split(/(\s+)/).filter((x) => x.trim().length>0).length
Example
In the following example, we take a string in str
, find the number of words in the string, and display the count in pre#output.
index.html
ADVERTISEMENT
Conclusion
In this JavaScript Tutorial, we learned how to count the number of words in given string, with example program.