Javascript: Count the occurrences of each word in a string

Last updated on June 23, 2022 A Goodman Loading... 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(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

Conclusion

We’ve gone over two examples of counting occurrences of words text. If you’d like to explore more new and useful stuff in modern Javascript, take a look at the following articles:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles