How to count the occurrences of each word in a string with JavaScript

1 Answer

0 votes
function countWordOccurrences(str) {
    // Convert the string to lowercase and split it into words
    const words = str.toLowerCase().match(/\b\w+\b/g);
    
    // Create an object to store word counts
    const wordCounts = {};

    // Iterate over each word and count occurrences
    words.forEach(word => {
        wordCounts[word] = (wordCounts[word] || 0) + 1;
    });

    return wordCounts;
}

const str = "JavaScript, often abbreviated as JS, is a programming language " + 
            "and core technology of the World Wide Web, alongside HTML " + 
            "and CSS. Ninety-nine percent of websites use JavaScript on " + 
            "the client side for webpage behavior";
             
const wordOccurrences = countWordOccurrences(str);

console.log(wordOccurrences);

 
    
/*
run:
    
{
  javascript: 2,
  often: 1,
  abbreviated: 1,
  as: 1,
  js: 1,
  is: 1,
  a: 1,
  programming: 1,
  language: 1,
  and: 2,
  core: 1,
  technology: 1,
  of: 2,
  the: 2,
  world: 1,
  wide: 1,
  web: 1,
  alongside: 1,
  html: 1,
  css: 1,
  ninety: 1,
  nine: 1,
  percent: 1,
  websites: 1,
  use: 1,
  on: 1,
  client: 1,
  side: 1,
  for: 1,
  webpage: 1,
  behavior: 1
}

*/

 



answered Mar 1, 2025 by avibootz
...