Friday, 25 January 2013

Word Count of input string in JavaScript



JavaScript Code:
<script type="text/javascript">
function WordCount(obj) {
            var RetVal = 0;
            var WStr;
            var TmpArr = new Array();
           
            try {
                WStr = $.trim($(obj).val());
               
                if(WStr.length ==0){
                    RetVal = 0;
                }
                else {
                    WStr = WStr.replace(/\s/g,'+');
                    WStr = WStr.replace(/^\s/g,'+');
                    WStr = WStr.replace(/\+*$/gi,"");
                    WStr = WStr.replace(/\++/g,' ');

                    TmpArr = WStr.split(' ');

                    RetVal = TmpArr.length;
                }
            }
            catch (err) { }

            return RetVal;
      }

      function SetWordCount(obj){
            $("#WCount").html(WordCount(obj));
}
</script>

Html Code:
<input type="text" onkeyup="SetWordCount(this);" style="width:50%;" />
<br />
Word Count : <label id="WCount"></label>

No comments:

Post a Comment