Count the Number of Words in a TextArea using jQuery

If you were looking out for a script to count the number of words in a TextArea, then here it is:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Count Words in a TextArea</title>

<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function() {
$("#btnCount").click(function() {
var strText = jQuery.trim($('#txtArea').val());
alert('Total No of Words are: ' + strText.split(/\s+/).length);
});
});
</script>
</
head>
<
body>
<
div>
<
textarea id="txtArea" cols="20" rows="10">
</
textarea>
<
br />
<
input id="btnCount" type="button" value="Count Words" />
</
div>
</
body>
</
html>

OUTPUT

image

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

Thanks!! after many many tries, jQuery.trim($('#txtArea').val()) works for me!