jQuery character and word count

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

Answers (2)

gotofritz
gotofritz

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

gdoron
gdoron

Reputation: 150253

<span id="elementId">
We have here 8 words and 35 chars
</span>​

var text = $('#elementId').text();
var charsLength = text.length;           //35
var wordsCount = text.split(' ').length; //8

Live DEMO

Upvotes: 3

Related Questions