How to count words in JavaScript using JQuery

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

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

A slight improvement on other answers as is deals with more edge cases. ie using multiple spaces and punctuation together and also handles punctuation at the start and end of text properly.

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

It first strips off any punctuation and spaces at the beginning and end of the text and then counts what's left. Obviously one can add more punctuation (like exclamation marks) if required.


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