
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Number of Occurrences for Each Character in a String with JavaScript
Take an array to store the frequency of each character. If similar character is found, then increment by one otherwise put 1 into that array.
Let’s say the following is our string −
var sentence = "My name is John Smith";
Following is the JavaScript code to count occurrences −
Example
var sentence = "My name is John Smith"; sentence=sentence.toLowerCase(); var noOfCountsOfEachCharacter = {}; var getCharacter, counter, actualLength, noOfCount; for (counter = 0, actualLength = sentence.length; counter < actualLength; ++counter) { getCharacter = sentence.charAt(counter); noOfCount = noOfCountsOfEachCharacter[getCharacter]; noOfCountsOfEachCharacter[getCharacter] = noOfCount ? noOfCount + 1: 1; } for (getCharacter in noOfCountsOfEachCharacter) { if(getCharacter!=' ') console.log("Character="+getCharacter + " Occurrences=" + noOfCountsOfEachCharacter[getCharacter]); }
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo40.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo40.js Character=m Occurrences=3 Character=y Occurrences=1 Character=n Occurrences=2 Character=a Occurrences=1 Character=e Occurrences=1 Character=i Occurrences=2 Character=s Occurrences=2 Character=j Occurrences=1 Character=o Occurrences=1 Character=h Occurrences=2 Character=t Occurrences=1
Advertisements