How to count the occurrences of each word in a string with Node.js

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 = "Node.js is a cross-platform, open-source JavaScript " + 
            "runtime environment that can run on Windows, Linux, Unix, " + 
            "macOS, and more. Node.js runs on the V8 JavaScript engine, " + 
            "and executes JavaScript code outside a web browser.";
             
const wordOccurrences = countWordOccurrences(str);

console.log(wordOccurrences);


 
    
/*
run:
    
{
  node: 2,
  js: 2,
  is: 1,
  a: 2,
  cross: 1,
  platform: 1,
  open: 1,
  source: 1,
  javascript: 3,
  runtime: 1,
  environment: 1,
  that: 1,
  can: 1,
  run: 1,
  on: 2,
  windows: 1,
  linux: 1,
  unix: 1,
  macos: 1,
  and: 2,
  more: 1,
  runs: 1,
  the: 1,
  v8: 1,
  engine: 1,
  executes: 1,
  code: 1,
  outside: 1,
  web: 1,
  browser: 1
}

*/
 
 

 



answered Mar 1, 2025 by avibootz

Related questions

2 answers 122 views
3 answers 335 views
2 answers 137 views
2 answers 179 views
1 answer 117 views
...