JavaScript Word Count


/ Published in: JavaScript
Save to your folder(s)

Javascript code for counting the number of words in a sentence. It can be used to allow only a certain number of words.


Copy this code and paste it in your HTML
  1. function WordCount() {
  2. var wordsallowed = 300;
  3. var inp = document.getElementById('txtabstract').value;
  4.  
  5. var regex = /\s+/gi;
  6. var wordcount = jQuery.trim(inp).replace(regex, ' ').split(' ').length;
  7. if (wordcount <= wordsallowed) {
  8. chars = inp.length;
  9. } else {
  10. var text = inp.val();
  11. var new_text = text.substr(0, chars);
  12. document.getElementById('txtabstract').value=new_text;
  13. wordcount--;
  14. }
  15. $("#labelcount").html(wordcount);
  16. }

URL: http://www.classgist.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.