JavaScript Text Length Tool

I quite often find myself needing to know how long a string is, especially when testing form validation or when trying to write a page description. I therefore like to have this little tool to help me by simply counting the number of characters in a given string.

Use the JavaScript text length tool here.

The tool uses a single form with a textarea and a text box. The textarea has onkeyup and onkeydown events which causes it to call a function that counts the number of characters and enters this into the text box.

<form onsubmit="return false;" action="" id="textLengthCalc">
<textarea name="textarea" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
<input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
</form>

The following is the JavaScript function that is called when anything is put into the textarea. The function finds the form and then trims any white space from the textarea's contents before entering how long the string is into the text box.

function textCounter(){
 var area = document.getElementById('textLengthCalc');
 area.len.value = area.textarea.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '').length;
}

A simple bit of CSS styling makes the tool slightly more usable.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
19 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.