Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 words in string

Count number of words in string using JavaScript

As a very new programmer I would like to perform this function without the use of any regular expressions. I don't know anything about regex and so I want to use regular code, even if it is not the most effective way in the real world, for the sake of learning.

I cannot find any answer to my question elsewhere, so I thought I would ask here before I default to just using a regex.

    function countWords(str) {
      return str.split(/s+/).length;
    }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
598 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

function WordCount(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...