Word Count (jQuery/Javascript)
By | Wednesday, January 11, 2012


Hide Comments






Code:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function cw(){
var str = $("#str").val(); //STRING FROM "INPUT" TAG
str = $.trim(str); //TRIMS SPACES FROM LEFT & RIGHT
if(str){
var l = str.length; //NUMBERS OF CHARACTERS (INCLUDING SPACES)
var words = str.split(" ").length; //COUNTS WORDS BY SPLITING THEM BY ONE SPACE
//NOTE: BY DEFAULT, TWO OR MORE SPACES IN A ROW COUNT AS ONE "WORD"
for(i=0; i<l; i++){
if(str.substr(i, 2)==" "){
words--; //"FOR LOOP" DISQUALIFIES TWO OR MORE SPACES TO COUNT AS A "WORD"
}
}
}
{
words = 0;
}
$("#words").html(words);
}
</script>
<body>
<input id="str"> <input id="b" onClick="cw()" type="button" value="Count Words">
<div id="words"></div>
</body>
</head>
</html>