Home : Internet : JavaScript : Text : Word Count

Count Words Using JavaScript

Counting the number of words in a block of text is quite simple with JavaScript. The idea is to count the number of spaces and use this to calculate the number of words. Note that this will give an accurate result only as long as there are no extra spaces in the text.

The following example illustrates the script (you can paste your own text here if you like):


To use this script, place the following code in the document head:

function countWords(){
document.form1.wordcount.value = document.form1.inputString.value.split(' ').length;
}

Place the following code in the document body:

<form name="form1" method="post">
<textarea name="inputString" cols="50" rows="4">Text to count</textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();"> 
<input name="wordcount" type="text" value="" size="6">
</form>

You can adapt this script to count words in whichever way you like. The important part is inputString.value.split(' ').length — this counts the spaces.

Subscribe to us on YouTube