Share on Google+Share on Google+

JavaScript Count Words

Advertisement
In this section, you will learn how to count words written in text area.

JavaScript Count Words

In this section, you will learn how to count words written in text area. For this, we have created a text area to allow the user to enter words of their choice. The javascript takes the value of the text area and using the regular expression, determine the number of words and finally display it in the textbox. This whole functioning is done through onkeyup event that will display the number of the words in the textbox as the user enter the words in the text area.

Here is the code:

<script language="JavaScript">
function
Draft(text1,text2){
var v1=text1.value;
var v = 0;
v2=v1.replace(/\s/g,' ');
v2=v2.split(' ');
for (i=0; i<v2.length; i++) {if (v2[i].length > 0) v++;}
text2.value=v;
}
</script>
<
form name="form">
<
table>
<
tr>
<
td>Draft Your Ad here:</td>
<
td><textarea name="DraftAd" cols="15" rows=
"2"
onkeyup="Draft(this,document.form.Count)"></textarea></td>
</
tr>
<
tr>
<
td>No of words:</td>
<
td><input name="Count" type="text" value="0"></td>
</
tr>
</
table>
</
form>

Output

On specifying words in the text area, you will get the following output:

Advertisements

Posted on: August 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.