Javascript / JQuery:如何统计用逗号分隔的单词?

前端之家收集整理的这篇文章主要介绍了Javascript / JQuery:如何统计用逗号分隔的单词?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用Javascript

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

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

HTML:

示例(单词始终用逗号分隔):

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
count: (5 - 3) = 2

因此,我需要计算用逗号分隔的单词数量,但是例如如示例3所示,只有当逗号后面还有单词时,才应将它们计为3个单词.

并且不应允许用户输入超过5个单词.

最佳答案
就像是:

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

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

jsFiddle示例:http://jsfiddle.net/BzN5W/

编辑:

更好的例子:http://jsfiddle.net/BzN5W/2/

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

    if(words.length > 5){
        //alert("Hey! That's more than 5 words!");
        e.preventDefault();
    }
});
原文链接:https://www.f2er.com/jquery/428529.html

猜你在找的jQuery相关文章