A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters
a a that counts as 10 characters to me.....
From my perspective, Characters can just be
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the
\b word boundary markers when dealing with either
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
var text = this.value,
// replace all words with an x
xWords = text.replace(/\S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/\n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.