lumian
lumian

Reputation: 35

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?

Upvotes: 2

Views: 309

Answers (3)

user663031
user663031

Reputation:

If you are willing to relax your limitation on using regexp, you can do this directly, without using split:

sentence.match(/\w+/g).length

This means match any sequence of characters (\w) with a length of one or more (+), globally (g). It will return an array of matches, the length of which will give the number of words.

In order to protect against the case where there are no words in the string, and match will return null, you should actually write:

(sentence.match(/\w+/g) || []).length

which is still a few characters shorter than the alternative

sentence.split(' ').filter(Boolean).length

in case you worry about such things.

Upvotes: 2

Aditya Singh
Aditya Singh

Reputation: 16720

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

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

Upvotes: 0

Tom Walters
Tom Walters

Reputation: 15616

Just filter out blank values:

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

Upvotes: 5

Related Questions