JavaScript Count Words


 

JavaScript Count Words

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

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:

Ads