Skip to main content
Known Participant
September 16, 2010
Question

word count of a textarea

  • September 16, 2010
  • 3 replies
  • 1551 views

I want to calculate the word count of a textarea and display the value in the text "textcount".

The following code work for Firefox 3.6.9 & Chrome 6.0 & IE 7.

However, the initial word count for an empty textarea is 1 for IE 7.

OS is Windows XP Pro SP3.

How to code which will work for all browsers?

var countField = eval("fieldObj.form."+"textcount");

var wordcount = fieldObj.value.split(/\s+/g).length;

if (wordcount > 0)
  if (navigator.appName != 'Microsoft Internet Explorer')
       wordcount = wordcount - 1;
countField.value = wordcount;
This topic has been closed for replies.

3 replies

BKBK
Community Expert
Community Expert
December 24, 2010

I made a slight modification to the code in the reference. Save the following code as wordCount.html. Open it in the browser and test.

<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>

<script type=""text/javascript"">
var numberOfWords;
function wordcount(str) {
var text = str.trim();
var numberOfWords = text.split(/\s/);
if(text == '')  {
numberOfWords = 0;
} else {
numberOfWords = numberOfWords.length;
}
var elem = document.getElementById('w_count');
elem.value = numberOfWords;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>

tclaremont
Inspiring
January 13, 2011

If you dont have to be 100 percent accurate, you might consider just counting the number of blank spaces, instead of the number of words. This way you are looking for something precise, instead of a string that may have a varying number of characters.

commadelimited
Known Participant
December 9, 2010

What are you considering a "word"? More than 2 characters? More than 3 characters? Any string seperated by a space?

this is a test <-- how many words would this be for you? 2? 4? 3?

I wrote a plugin for the jQuery JavaScript library which counts the number of characters in a textarea field:

http://andymatthews.net/code/textCounter/

With a little work it could probably be converted to count words, upwards.

September 17, 2010