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. 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(){
	s = document.getElementById("inputString").value;
	s = s.replace(/(^\s*)|(\s*$)/gi,"");
	s = s.replace(/[ ]{2,}/gi," ");
	s = s.replace(/\n /,"\n");
	document.getElementById("wordcount").value = s.split(' ').length;

Place the following code in the document body (modify as required):

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


Subscribe to us on YouTube