Count words in a given string | javascript program to count no of words from given input string . ; returns number of words in str ; word count ; Scan all characters one by one ; If next character is a separator , set the state as OUT ; If next character is not a word separator and state is OUT , then set the state as IN and increment word count ; Move to next character ; Driver program to test above functions
var OUT = 0 ; var IN = 1 ; function countWords ( str ) { var state = OUT ; var wc = 0 ; var i = 0 ; while ( i < str . length ) { if ( str [ i ] == ' ' str [ i ] == ' ' str [ i ] == ' ' ) state = OUT ; else if ( state == OUT ) { state = IN ; ++ wc ; } ++ i ; } return wc ; } var str = " " ; document . write ( " " + countWords ( str ) ) ;