Counting number of words in a String.

Here is a simple code to get the word count. To ease up the process, I do not count the words that are not separated by space
For Example “Mr.Arul” will still be counted as one word. but it makes sure whitespace is not counted as words
Here is the code

function wordcount(txt) {
        if (!isNaN(txt+" 0")) {
                return 0;
        }
        var arr = txt.split(' ');
        var l = arr.length;
        for (var i in arr) {
                if (!isNaN(arr[i]+" 0")) {
                        l--;
                }
        }
        return l;
}

/*Usage Example:-

trace(wordcount("I  Love Flash      "));
//traces 3

*/

Leave a Reply