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.
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.
My overall goal is to find the shortest word in the string.
that's a pletely different question, though, isn't it?
– VLAZ
Commented
Nov 2, 2016 at 16:56
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"));
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.