Javascript/JQuery : How do I count the words separated with a comma?

标签 javascript jquery regex count

Javascript:

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

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

HTML:

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

示例(单词总是用逗号分隔):

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

因此,我需要计算有多少个单词以逗号分隔,但例如示例 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(" ", "");
    var words = value.split(",");

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

关于Javascript/JQuery : How do I count the words separated with a comma?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369411/

相关文章:

javascript - Dropzone 未提供 URL/Dropzone 已附加

javascript - 修改后的 jQuery API $.when() 在超时时返回未定义

javascript - 服务器的安全 ajax GET/POST 请求

javascript - 更改变量脚本

python - 获取包含换行符的列表

html - 用于在末尾查找、复制和插入的正则表达式

javascript - 如何使用 JavaScript 切换 SVG 圆圈

javascript - 无法使用 jQuery 获取 html 表中的同级值

javascript - JQuery UI 工具提示 - 调用 ajax 后不透明度被破坏。

regex - PHP preg_match_all 限制