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> <br> <input type="button" name="Convert" value="Count Words" onClick="countWords();"> <input name="wordcount" type="text" value="" size="6">
Notes:
- You can adapt this script to count words in whichever way you like. The important part is s.split(' ').length — this counts the spaces.
- The script attempts to remove all extra spaces (double spaces etc) before counting.
- If the text contains two words without a space between them, it will count them as one word, e.g. "First sentence.Start of next sentence".