After getting some help working through my bugs, I have what seems to
be a robust, working word counter script. I post it here to benefit
others that might want this in the future and so that if I ever lose
my copy I can come back here to find it :) Some other scripts that I
used for inspiration failed when confronted with whitespace before the
string or miscalculated when encountering linefeeds and other
non-space spaces, so I made mine better. Definition of words for this
exercise is contiguous groups of characters separated by whitespace.
Maybe it will even be useful to somebody besides me.
Cheers!
--David
<html>
<!--Generated 02/12/04-->
<!--modified 02/15/04-->
<!--name of this file: "wordCounter.html" -->
<head>
<title>Word Counter</title>
<SCRIPT LANGUAGE="JavaScript">
function trim(data)
{
while (/\s/.test(data.charAt(0)))
{data=data.substring(1,data.length);}
while (/\s/.test(data.charAt(data.length-1)))
{data=data.substring(0,(data.length-1));}
return data;
}
function countWords()
{
var input, wordList, output;
input=document.forms[0].elements[0].value;
input=trim(input);
wordList=input.split(/\s+/g);
output=wordList.length;
document.forms[0].elements[0].focus();
return output;
}
</SCRIPT>
</head>
<body bgcolor="#666666"
text="#00ff00"
link="#ffffcc"
vlink="#ffffcc">
Enter or paste text into the box below and press <b>count</b> to see
the total number of words.
<br>
<br>
<form onSubmit="return false">
<center>
<textarea rows="30" cols="100"></textarea>
<br>
<br>
<button onClick="alert('total words = ' + countWords())"
class="button">count</button>
</center>
</form>
</body>
</html>