Search code examples
jquerytextareaword-count

How to do a javascript word count that excludes single character words


I want to run a script to count the words in a textarea, which excludes all single letter words. So if someone enters the sentence "This is a word count" I want the count to be 4 as it excluded "a".

I have pretty basic jQuery knowledge but was able to get the word count including single letter words:

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();

Would I be looking to do something like

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

I can't seem to find anything that does this and it's probably simple, please help :)


Solution

  • You can avoid single letter words by amending your Regex to \b\w{2,}. This will look for a word boundary followed by a word of 2 characters or longer.

    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>

    Also note that the each() loop in the event handler is redundant as the id will only ever select a single element. If you want this to work for multiple elements, use a common class on them all:

    $(".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>