Calculate number of words and characters (/statistics) from an HTML Textarea var textarea = document.getElementById("textarea"),
  statusBar = document.getElementById("status-bar");
    function updateStatusBar() {
      var text = textarea.value,
        chars = text.length,
        words = text.split(/\b\S+\b/g).length - 1,
        lines = text.split("\n").length;
      statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
    }
I will give it a try:


These days I would recommend using document.querySelector, to write generic code which is well amenable to code re-factoring without introducing bugs.

So either:

var  textarea = document.querySelector("#my-textarea")
    ,statusBar = document.querySelector("#status-bar");


or in later JavaScript versions, I believe >=1.6 (i.e. OK Server-side, when a specific JS-runtime can be guaranteed):

var [eltxtarea, elstatusbar] = document.querySelectorAll("#my-textarea,#status-bar");

Do not assign elements to Id's that are also keywords/attributes in the HTML specification (as such not textarea but e.g. my-textarea )
Bind the invocation of your function to an event or directly to underlying data-changes(requiring additional frameworks such as backbone.js). Do not use the respective exposed handler attribute but rather the attachEventHandler.

elstatusbar.attachEventHandler( "change", changeHandlerStatusbarUpdate);



The Handler:

    var changeHandlerStatusbarUpdate = function(evt){
        if(evt instanceof Event &amp;&amp; evt.target instanceof HTMLTextAreaElement){ 
        //you can be more specific. Event is just the Baseclass.
        //for instance you may test for "KeyboardEvent" only

        //the following logic should be improved: See threads of how to count words in a language/culture-specific fashion
            var text = textarea.value,
            chars = text.length,
            words = text.split(/\b\S+\b/g).length - 1,
            lines = text.split("\n").length,
            stat = lines + " lines, " + words + " words, " + chars + " characters";
            evt.target.value = stat;
        }
    }



Do not put the updateStatusBar function in the global or window scope when the function relies upon textarea in the outside-scope, but use scope-encapsulation via closures (example), or a retrieve the target element within the function or through the event-target in a handler-function.


As pointed out in the source-comment, the word-counting is much to trivial and not "culture-invariant" as is the case right now.