Word Counter using Javascript


This code will work to count the words entered in the textbox.



<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="WordCountTextBox" TextMode="multiLine" MaxLength="100" 
          runat="server" onkeyup="javascript:WordCounter(this.id,'MessageLabel');"
          onblur="javascript:WordCounter(this.id,'MessageLabel');">
         </asp:TextBox>
        <asp:Label ID="MessageLabel" runat="server" Text="100 chars
        remaining"></asp:Label></div>
    </form>
</body>


Place this code in the header tag.


<script language="javascript" type="text/javascript">
        function WordCounter(WordCountTextBox, MessageLabel) {
            var this_field = document.getElementById(WordCountTextBox);
            var label = document.getElementById(MessageLabel);
            var char_count = this_field.value.length;
            var fullStr = this_field.value + " ";
            var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
            var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
            var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
            var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
            var splitString = cleanedStr.split(" ");
            var word_count = splitString.length - 1;
            if (fullStr.length < 2) {
                word_count = 0;
            }
            if (word_count == 1) {
                wordOrWords = " word";
            }
            else {
                wordOrWords = " words";
            }
            if (char_count == 1) {
                charOrChars = " character";
            }
            else {
                charOrChars = " characters";
            }
            label.innerHTML = word_count + wordOrWords;
        }
    </script>
Vikram Chandra Theme by BloggerThemes & NewWPThemes Sponsored by iBlogtoBlog