Count number of words using JavaScript

To count the number of words present inside a textbox or in a string variable is very easy and simple task. The trick is to use split() function of the Javascript. spilt() function takes delimiter as argument.

So we will be assuming that number of words is equal to the number of spaces present in the text and we will count the number of spaces present in the text using the split() function. Check out the examples given below.

Count number of words in a textbox (DEMO) 


Here is the complete code for the above example.

<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4">This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input type="button" name="Count" value="Count Words" onClick="countNoOfWords();" />  <input name="noofwords" type="text" value="" size="6" />

<script type="text/javascript"> 

function countNoOfWords(){

document.myform.noofwords.value = document.myform.inpString.value.split(' ').length;



Count number of words in a string variable

<script type="text/javascript">
var myString = "Hi this is a sample text";
var mySplitResult = myString.split(" ");