Javascript / jQuery: How to count words separated by comma?

JavaScript:

$(document).ready(function()
{
    $('#field').keyup(function()
    {
        var count = '??';

        $('#count').html(count);
    });
});

HTML:

<input type="text" id="field" /> <span id="count">5</span>

Examples (words are always separated by a comma):

example 1: word, word word
count: (5 - 2) = 3

example 2: word
count: (5 - 1) = 4

example 3: word, word,
count: (5 - 2) = 3

example 4: word, word, word
count: (5 - 3) = 2

So, I need to calculate how many words are separated by a comma, but, for example, as shown in example 3 , it should not be counted as 3 words only when there is a word also AFTER the comma.

And the user is not allowed to enter more than 5 words.

+5
source share
3 answers

Sort of:

$("#input").keyup(function(){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");

    if(words.length > 5){
        alert("Hey! That more than 5 words!");
        $(this).val("");
    }
});

JsFiddle example: http://jsfiddle.net/BzN5W/

EDIT:

Best example: http://jsfiddle.net/BzN5W/2/

$("#input").keypress(function(e){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");

    if(words.length > 5){
        //alert("Hey! That more than 5 words!");
        e.preventDefault();
    }
});
+9
source

words.split(",").length , , words - , .

0

, :

$('#field').keyup(function(e){
    var count = $(this).val().split(',').length;
    $('#count').html(count);
    if(count > 4)
        e.preventDefault();
});
0

All Articles