Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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
...