Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

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 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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...