gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:56:10 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com