lumian lumian - 2 years ago 115
Javascript Question

String word count without using regex?

I'm trying to figure out an effective way to do a word count for a given string in JavaScript, without the use of regex.

The following works for some strings:

function wordCount(str) {
return str.split(" ").length;

console.log(wordCount("howdy there partner"));

However - when given a string like, " this is an example " the word count goes to 6 instead of 4. Additionally, this approach will not work for empty strings, like "" or " " (will return a word count of 1 and 2, respectively).

Is there any way to do an accurate word count for these instances, without the use of regex?

Answer Source

Just filter out blank values:

function wordCount(str) {
    return str.split(' ').filter(function(val){ return val != '' }).length
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download