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

1 Answer

0 votes
function countWordOccurrences(str: string): { [key: string]: number } {
  // Convert the string to lowercase and split it into words
  const words: RegExpMatchArray | null = str.toLowerCase().match(/\b\w+\b/g);

  // Create an object to store word counts
  const wordCounts: { [key: string]: number } = {};

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

  return wordCounts;
}

const str: string =
  "TypeScript (TS) is a free and open-source high-level " +
  "programming language developed by Microsoft that adds " +
  "static typing with optional type annotations to JavaScript. " +
  "It is designed for the development of large applications " +
  "and transpiles to JavaScript";

const wordOccurrences = countWordOccurrences(str);

console.log(wordOccurrences);

 
    
/*
run:
    
{
  "typescript": 1,
  "ts": 1,
  "is": 2,
  "a": 1,
  "free": 1,
  "and": 2,
  "open": 1,
  "source": 1,
  "high": 1,
  "level": 1,
  "programming": 1,
  "language": 1,
  "developed": 1,
  "by": 1,
  "microsoft": 1,
  "that": 1,
  "adds": 1,
  "static": 1,
  "typing": 1,
  "with": 1,
  "optional": 1,
  "type": 1,
  "annotations": 1,
  "to": 2,
  "javascript": 2,
  "it": 1,
  "designed": 1,
  "for": 1,
  "the": 1,
  "development": 1,
  "of": 1,
  "large": 1,
  "applications": 1,
  "transpiles": 1
} 

*/
  

 



answered Mar 1, 2025 by avibootz
...