JavaScript Word Counter
I found this neat tool on a site to do with search engine optimisation, which counts the number of words that are typed into a textarea. I have tried all sorts of patterns and characters and it seems very robust.
The tool uses a textarea of a form and outputs the number of words into an input box in the same form. Here is the HTML. The textarea calls a function called textCounter() every time a key is pressed.
<form onsubmit="return false;" action="" id="wordCountCalc">
<textarea name="message1" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
<input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
</form>
The function works by removing any white space from the start of the text. It then removes any tab characters from the text before splitting the text by one or more white space characters.
The first step is to detect what browser the user is viewing the site in due to a discrepancy between how different browsers split a string apart by white space. The following snippet is used to detect browsers.
var sUserAgent = navigator.userAgent;
var isOpera = sUserAgent.indexOf("Opera")>-1;
var isIE = sUserAgent.indexOf("compatible")>1 && sUserAgent.indexOf("MSIE")>1 && !isOpera;
Here is the function that counts the number of characters in the textarea element.
function textCounter(){
var area = document.getElementById('wordCountCalc');
var formcontent;
if(area.message1.value.length != 0){
var reg;
reg = /^\s/gi;
formcontent = area.message1.value.replace(reg,''); // remove white space at start or string
reg = /\t+/g;
formcontent = formcontent.replace(reg,' '); // remove any tab characters
reg = /\s+/g;
formcontent = formcontent.split(reg); // split string by spaces
if(isIE){
area.len.value = formcontent.length;
}else{
if(area.message1.value.charAt(area.message1.value.length-1)==' ' || area.message1.value.charAt(area.message1.value.length-1)=='\n'){
area.len.value = formcontent.length-1;
}else{
area.len.value = formcontent.length;
};
};
}else{
area.len.value = 0;
};
};
Write a comment