text: Count words in a given string | Function to count total number of words in the string ; Check if the string is null or empty then return zero ; Converting the given string into a character array ; Check if the character is a letter and index of character array doesn 't  equal to end of line that means, it is  a word and set isWord by true ; Check if the character is not a letter that means there is a space , then we increment the wordCount by one and set the isWord by false ; Check for the last word of the sentence and increment the wordCount by one ; Return the total number of words in the string ; Given String str ; Print the result
code: function countWords ( str ) { if ( str == null str . length == 0 ) return 0 ; let wordCount = 0 ; let isWord = false ; let endOfLine = str . length - 1 ; let ch = str . split ( " " ) ; for ( let i = 0 ; i < ch . length ; i ++ ) { if ( isLetter ( ch [ i ] ) && i != endOfLine ) isWord = true ; else if ( ! isLetter ( ch [ i ] ) && isWord ) { wordCount ++ ; isWord = false ; } else if ( isLetter ( ch [ i ] ) && i == endOfLine ) wordCount ++ ; } return wordCount ; } function isLetter ( c ) { return c . toLowerCase ( ) != c . toUpperCase ( ) ; } let str = " " ; document . write ( " " + countWords ( str ) ) ;