【问题标题】:How to do a javascript word count that excludes single character words如何进行不包括单个字符单词的javascript字数统计
【发布时间】:2020-07-27 03:36:45
【问题描述】:

我想运行一个脚本来计算文本区域中的单词,其中不包括所有单字母单词。 因此,如果有人输入句子“这是一个字数”,我希望计数为 4,因为它排除了“a”。

我有相当基本的 jQuery 知识,但能够获得包括单字母单词在内的字数:

var wordCounts = {};
    jQuery("#65").keyup(function() {
        var matches = this.value.match(/\b/g);
        wordCounts[this.id] = matches ? matches.length / 2 : 0;
        var finalCount = 0;
        jQuery.each(wordCounts, function(k, v) {
            finalCount += v;
        });
        console.log(wordCounts);
    }).keyup();

我是否想做类似的事情

if (matches.length >= 2) {
 finalCount += v;
}

我似乎找不到任何可以做到这一点的东西,它可能很简单,请帮助:)

【问题讨论】:

    标签: jquery textarea word-count


    【解决方案1】:

    您可以通过将 Regex 修改为 \b\w{2,} 来避免使用单个字母的单词。这将寻找一个单词边界,后跟一个 2 个字符或更长的单词。

    var wordCounts = {};
    
    jQuery("#65").on('input', function() {
      var matches = this.value.match(/\b\w{2,}/g).length;
      wordCounts[this.id] = matches; 
      console.log(wordCounts);
    }).trigger('input');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="65">This is a word count</textarea>

    还要注意,事件处理程序中的each() 循环是多余的,因为id 只会选择单个元素。如果您希望这适用于多个元素,请在所有元素上使用一个公共类:

    $(".count").on('input', function() {
      console.log(getWordCounts());
    });
    
    function getWordCounts() {
      let wordCounts = {};
      $('.count').each((i, el) => wordCounts[el.id] = el.value.match(/\b\w{2,}/g).length);
      return wordCounts;
    }
    
    console.log(getWordCounts());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="65" class="count">This is a word count</textarea>
    <textarea id="foo" class="count">Lorem ipsum dolor sit amet consectetur adipiscing elit</textarea>

    【讨论】:

    • 谢谢,太完美了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多