Reputation: 446
This is a really simple question. Is it possible for jQuery to get an element, and count the number of words AND characters in that element (not a textarea or input) and echo it out on a HTML document? The only code that I could think of that may work is:
document.write("$('.content').text().length;")
I'm really bad at jQuery, but I'm trying to learn it. If anyone could provide a script, that'd be helpful.
Upvotes: 3
Views: 19126
Reputation: 3381
var txt = $('.content')[0].text()
, charCount = txt.length
, wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length
;
$( '#somwhereInYourDocument' ).text( "The text had " + charCount + " characters and " + wordCount +" words" );
Running replace before split to get rid of punctuation, and running split with a regular expression to deal with new lines, tabs and multiple spaces in between words.
EDIT added the text( ... ) bit to write to a node, as the OP specified in a comment to another answer.
EDIT you still need to wrap it in a function to make it work after page load
$( function(){
var txt = $('.content')[0].text()
, charCount = txt.length
, wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length
;
$( '#somwhereInYourDocument' ).text( "The text had " + charCount + " characters and " + wordCount +" words" );
});
Otherwise it runs before anything has been rendered on the page
Upvotes: 11