-2

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.

Community
  • 1
  • 1
Mote Zart
  • 861
  • 3
  • 17
  • 33
  • 2
    http://stackoverflow.com/questions/18679576/counting-words-in-string?noredirect=1&lq=1 this is your first link, the accepted answer does it without regex. Does that not work? – VLAZ Nov 02 '16 at 16:49
  • 1
    How would you count the words in a string manually? You would put your finger at the start of the string, see if the word you wanted was there, and then move your finger to the next character in the string. Repeat until your finger is at the end of the string. Now do that, but in JS code. – RB. Nov 02 '16 at 16:50
  • Could just use [String.split()](http://www.w3schools.com/jsref/jsref_split.asp) to split the string into an array by splitting them by space. Also what's your aversion to Regex? It would be part of the learning curve when learning to program – Harmelodic Nov 02 '16 at 16:50
  • Seems to me the links provided have sufficient material to answer your question. If not, after reading them, you should realize you need to add what word boundaries are for you. – ASDFGerte Nov 02 '16 at 16:50
  • `My overall goal is to find the shortest word in the string.` that's a completely different question, though, isn't it? – VLAZ Nov 02 '16 at 16:56
  • @Harmelodic I don't have a real aversion. Since I can't do it without one I thought it might be better to learn it first so I understand how to follow the solution. That was my reason for searching for an non-regular expression solution. Seems regex is the way to go. – Mote Zart Nov 02 '16 at 17:06

2 Answers2

1

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.

OK sure
  • 2,617
  • 16
  • 29
  • @MoteZart if you have multiple spaces (SO annoyingly trims them), then you still split on space and then remove all resulting empty strings – VLAZ Nov 02 '16 at 17:05
  • I tried this but when I put in spaces it seemed to add numbers. So "hello____ world" returns 4 for WordCount. Maybe my wanting a more "pure" answer was off base. If this only non-regex answer is all there is I'll except it, but I thought there might be a more involved one out there for handling this spacing issue so I could learn to manage this problem manually. edit: put in underscores for spaces – Mote Zart Nov 02 '16 at 17:09
  • @MoteZart `"hello____world".split(" ")` -> `["hello", "", "", "", "world"]` -> remove the empty strings -> `["hello", "world"]` -> count is now `2` – VLAZ Nov 02 '16 at 17:11
  • @viaz This means I need to review split since I see here that aside from your explanation, I do not know how to make a string of types into an array. I'm being directed to MDN for more info. Your explanation is clear though. – Mote Zart Nov 02 '16 at 17:29
  • @MoteZart I've edited to address the double space issue but it seems the question has changed slightly since then! This will clear out double spaces. – OK sure Nov 02 '16 at 18:05
1

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:

function WordCount(str) { 
    var words = str.split(" ");

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

console.log(WordCount("hello to the world"));
Fauphi
  • 360
  • 1
  • 2
  • 11
  • Adding `console.log('word count = ' + str.split(' ').filter(function(n) { return n != '' }).length);` in the 2nd line of the above code gives the count of words in the sentence along with the shortest word. – Nitin Bhargava Jun 08 '18 at 11:18