JavaScript: Count the occurrences of each word in a string

Updated: February 19, 2023 By: Khue Post a comment

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