How to count words in JavaScript using jQuery

I have a simple html text box. When I β€œsubmit” the form in which the text field is located, I would like to get a variable with the number of words inside using jQuery. I would also like to check if the entered text has only letters, numbers and hyphens (also in jquery). I do not need to count words as user types only when the form is submitted. The form will not be submitted if jquery is disabled, so I think there are no security risks without using php. It's 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 
+6
source share
6 answers

You would split the string and then calculate the length of the resulting array.

 $('input[type="submit"]').click( function() { var words = $('#name').val().split(' '); alert(words.length); }); 
+14
source

A slight improvement over other answers, as we are talking about a larger number of cases. those. Use multiple spaces and punctuation together, and correctly handle punctuation at the beginning and end of the text.

 var numOfWords = $('#name').val().replace(/^[\s,.;]+/, "").replace(/[\s,.;]+$/, "").split(/[\s,.;]+/).length; 

First, he discards any punctuation and spaces at the beginning and end of the text, and then counts what remains. Obviously, if necessary, you can add more punctuation marks (for example, exclamation points).

+6
source

It is very useful to remove spaces from the beginning and end of the line usign $.trim() . You can use the keyup event to count in real time.

 $('#name').keyup(function(){ var words = $.trim($(this).val()).split(' '); console.log(words.length); }); 
+2
source
 var str = $('#name').val(), count = str.split(' ').length; 

Assuming each word is separated by a space

+1
source

You can specify multiple characters to separate the original string:

 $('input[type="submit"]').click( function() { var words = $('#name').val().split(/[\s\.,;]+/); console.log(words.length); }); 
+1
source

Using the regex below, we can remove any white space (one or more) so that the counter is very accurate.

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

Check out this jQuery plugin I developed:

https://github.com/mcdesignpro/maxLenght

0
source

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


All Articles