Sling Academy
Home/JavaScript/JavaScript: Count the occurrences of each word in a string

JavaScript: Count the occurrences of each word in a string

Last updated: February 19, 2023

The example below shows you how to count the occurrences of each word in a given sentence in Javascript. The result will be an object where each key is a word, and the value is the number of occurrences of the corresponding word, like this:

{
  'word1': 2,
  'word2': 1,
   /* ... */
}

Example code (with explanation):

// define the function for reuse later
function countWordOccurrences(input) {
    // initialize the result object
    const result = {};
  
    // create an array from the input
    const arr = input.split(' ');
    
    // loop through the array
    for(let word of arr) {
      // if the word is already in the result object, increment the count
      if(result[word]) {
        result[word]++;
      } else {
        // otherwise, add the word to the result object with a count of 1
        result[word] = 1;
      }
    }
    
    return result;
  }
  
  // try the function
  console.log(countWordOccurrences('The brown dog jumped over the lazy dog when the brown fox was sleeping'));

Output:

{
  The: 1,
  brown: 2,
  dog: 2,
  fox: 1,
  jumped: 1,
  lazy: 1,
  over: 1,
  sleeping: 1,
  the: 2,
  was: 1,
  when: 1
}

Counting the occurrences of a specific word/substring

In case you want to count the occurrences of a specific substring in the parent string, do like the following example:

// define a reusable function
function countOccurrences(string, substring) {
  var n = 0;
  var position = 0;
  while (true) {
    position = string.indexOf(substring, position);
    if (position != -1) {
      n++;
      position += substring.length;
    } else {
      break;
    }
  }
  return n;
}

// test it
console.log(countOccurrences("a pan of bananas", "an")); 

Output:

3

Next Article: 3 Ways to Reverse a String in JavaScript

Previous Article: JavaScript: Regular Expressions Cheat Sheet

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration