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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5369411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:58:32  来源:igfitidea点击:

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

javascriptjqueryregexcount

提问by mattsven

Javascript:

Javascript:

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

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

HTML:

HTML:

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

Examples (words are always separated with 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 count how many words there are separated with a comma, but for example as shown in example 3, it should not count them as 3 wordsonly when there is a word also AFTER a comma.

因此,我需要计算用逗号分隔的单词数量,但例如如示例 3所示,仅当在逗号之后也有单词时,不应将它们计为3个单词。

And a user should not be allowed to enter more than 5 words.

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

回答by mattsven

Something like:

就像是:

$("#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 example: http://jsfiddle.net/BzN5W/

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

EDIT:

编辑:

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

更好的例子: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();
    }
});

回答by Fareesh Vijayarangam

words.split(",").lengthshould give you what you want, where wordsis a string containing the input.

words.split(",").length应该给你你想要的,words包含输入的字符串在哪里。

回答by Simeon

I think you are looking for this:

我想你正在寻找这个:

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