Counting words in string
Solution 1:
Use square brackets, not parentheses:
str[i] === " "
Or charAt
:
str.charAt(i) === " "
You could also do it with .split()
:
return str.split(' ').length;
Solution 2:
Try these before reinventing the wheels
from Count number of words in string using JavaScript
function countWords(str) {
return str.trim().split(/\s+/).length;
}
from http://www.mediacollege.com/internet/javascript/text/count-words.html
function countWords(s){
s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude start and end white-space
s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
return s.split(' ').filter(function(str){return str!="";}).length;
//return s.split(' ').filter(String).length; - this can also be used
}
from Use JavaScript to count words in a string, WITHOUT using a regex - this will be the best approach
function WordCount(str) {
return str.split(' ')
.filter(function(n) { return n != '' })
.length;
}
Notes From Author:
You can adapt this script to count words in whichever way you like. The important part is
s.split(' ').length
— this counts the spaces. The script attempts to remove all extra spaces (double spaces etc) before counting. If the text contains two words without a space between them, it will count them as one word, e.g. "First sentence .Start of next sentence".
Solution 3:
One more way to count words in a string. This code counts words that contain only alphanumeric characters and "_", "’", "-", "'" chars.
function countWords(str) {
var matches = str.match(/[\w\d\’\'-]+/gi);
return matches ? matches.length : 0;
}