Count Words and Characters [closed]

I've been looking to add a word and character count to a textarea using jQuery although all I've found are plugins to limit characters and words.

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

Is there a simple way to check for words and characters?

Answers:

Answer

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 wc = wordCount(this.value);
  result.innerHTML = (`
   <br>Characters (no spaces):  ${wc.charactersNoSpaces}
   <br>Characters (and spaces): ${wc.characters}
   <br>Words: ${wc.words}
   <br>Lines: ${wc.lines}
  `);
});
<textarea id="text" cols="30" rows="4"></textarea>
<div id="result"></div>

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

Read more

Answer

W/O jQuery:

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

With jQuery:

$(this).html()

etc.

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.