lumian lumian - 7 months ago 25
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

Just filter out blank values:

function wordCount(str) {
    return str.split(' ').filter(function(val){ return val != '' }).length
}
Comments