javascript: Word Counter

Posted: December 19, 2008 in ASP.NET, Javascript
Tags: , , , ,

Few months back I have posted one article on “Javascript: Maximum character validation and character counter for a textbox”, now here I have given one example on how to count words out of any textarea or textbox.

The counter of word will get incremented as you type in each word (one spell) into the textbox/textarea. This script will also work when anyone copy/paste the text into the textbox (copy/paste should not through mouse). Check the following script:

<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100"
runat="server" onkeyup="javascript:WordCounter(this.id,'Label1');"
onblur="javascript:WordCounter(this.id,'Label1');"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars
remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function WordCounter(textId,lblID)
{
var this_field = document.getElementById(textId);
var label = document.getElementById(lblID);
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>
</form>
</body>

Happy Coding!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s