JQuery Sign and Word Count

This is a very simple question. Is it possible for jQuery to get an element and count the number of words AND characters in that element (rather than a text field or input) and repeat it in an HTML document? The only code I could think of could work:

document.write("$('.content').text().length;") 

I am really bad at jQuery, but I am trying to learn this. If anyone could provide a script, that would be helpful.

+1
source share
2 answers
 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" ); 

Run replace before split to get rid of punctuation, and run split with a regex to process newlines, tabs, and a few spaces between words.

EDIT added a bit of text (...) to write to node, as the OP indicated in the comment to another answer.

EDIT , you still need to wrap it in a function to make it work after the page loads

 $( 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 starts before everything is displayed on the page.

+9
source
 <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

+1
source

Source: https://habr.com/ru/post/905278/


All Articles