Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count words in JavaScript using JQuery

I have a simple html text box. When I "submit" the form that the text box is in, I would like to get a variable with the number of words inside using Jquery. I would also like to check if the inputted text is only letters, numbers and hyphens (also in jquery). I do not need to count the words as the user types, just when the form is submitted. The form won't submit if jquery is turned off so I guess there are no security risks by not using php. Is this true?

HTML:

<input type='text' name='name' id='name' />
<input type='button' value='Sign Up' id='signUp'>

JQUERY (attempt):

var wordcount = $('#name').val()  // i don't know how to count the words 
like image 509
kirby Avatar asked Jan 06 '12 03:01

kirby


1 Answers

Using the regular expression below allow us to remove any kind of white space (single or multiples) so that the count is very accurate.

$('#name').keyup(function(){
   var wordCount = $(this).val().split(/[\s\.\?]+/).length;
   console.log(wordCount);
});

See this jQuery plugin I have developed:

https://github.com/mcdesignpro/maxLenght

like image 199
Marco Avatar answered Sep 27 '22 18:09

Marco