Skip to content Skip to sidebar Skip to footer

Use Javascript To Count Words In A String, Without Using A Regex

There are many posts on the topic of how to count the number of words in a string in JavaScript already, and I just wanted to make it clear that I have looked at these. Counting w

Solution 1:

Seems the question has changed a little but the first link in your post is close. Modified to ignore double spaces:

functionWordCount(str) {
   return str
     .split(' ')
     .filter(function(n) { return n != '' })
     .length;
}

console.log(WordCount("hello      world")); // returns 2

No regexes there - just explode the string into an array on the spaces, remove empty items (double spaces) and count the number of items in the array.

Solution 2:

So, here is the answer to your new question:

My overall goal is to find the shortest word in the string.

It splits the string as before, sorts the array from short to long words and returns the first entry / shortest word:

functionWordCount(str) { 
    var words = str.split(" ");

    var sortedWords = words.sort(function(a,b) {
        if(a.length<b.length) return -1;
        elseif(a.length>b.length) return1;
        elsereturn0;
    });
   return sortedWords[0];
}

console.log(WordCount("hello to the world"));

Post a Comment for "Use Javascript To Count Words In A String, Without Using A Regex"