JavaScript Text Length Tool

4th September 2009

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.

  1. <form onsubmit="return false;" action="" id="textLengthCalc">
  2. <textarea name="textarea" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
  3. <input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
  4. </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.

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

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.