Number of words and characters using jQuery

I wanted to add a word and number of characters to the text field using jQuery, although all I found were plugins to limit characters and words.

I would like to update in real time, so every time the user adds a character or word, the counter is updated.

Is there an easy way to check words and characters?

+5
source share
5 answers

function wordCount( val ){ var wom = val.match(/\S+/g); return { charactersNoSpaces : val.replace(/\s+/g, '').length, characters : val.length, words : wom ? wom.length : 0, lines : val.split(/\r*\n/).length }; } var textarea = document.getElementById("text"); var result = document.getElementById("result"); textarea.addEventListener("input", function(){ var v = wordCount( this.value ); result.innerHTML = ( "<br>Characters (no spaces): "+ v.charactersNoSpaces + "<br>Characters (and spaces): "+ v.characters + "<br>Words: "+ v.words + "<br>Lines: "+ v.lines ); }, false); 
 <textarea id="text"></textarea> <div id="result"></div> 

jsFiddle demo

+45
source
 char_count = $("#myTextArea").val().length; word_count = $("#myTextArea").val().split(" ").length; 
+6
source
 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" ); 

More details

0
source

W / O jQuery:

 this.innerHTML gives you the textarea content. this.innerHTML.length gives you the number of characters. 

Using jQuery:

 $(this).html() 

and etc.

I'm sure you can come up with a simple word count algorithm.

-1
source
 jQuery(document).ready(function(){ var count = jQuery("#textboxid").text().length; }); 
-1
source

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


All Articles