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
}
*/