Log In

Email:
Password:
Keep me logged in

Forgot Password

Email:




Social Media
     
CategoriesCSS (5)
jQuery (73)
PHP (30)
.htaccess (4)
Sponsored Links


Word Count
jQuery Javascript
Demo | Browse Category | Wednesday, January 11, 2012 by




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>
Views: 90 Likes: 0 Dislikes: 0