
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 char 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
- Related Questions & Answers
- How to count the number of occurrences of a character in a string in JavaScript?
- How to Count Occurrences of Each Character in String in Android?
- Count the number of occurrences of a string in a VARCHAR field in MySQL?
- Count occurrences of a character in string in Python
- Match multiple occurrences in a string with JavaScript?
- C# program to count the occurrences of each character
- Java program to count the occurrences of each character
- Pandas GroupBy – Count the occurrences of each combination
- Count occurrences of a character in a repeated string in C++
- Trying to get number for each character in string - JavaScript
- C# program to count occurrences of a word in string
- Java program to count occurrences of a word in string
- Count occurrences of the average of array elements with a given number in C++
- Python program to count occurrences of a word in a string
- Finding number of occurrences of a specific string in MySQL?
Advertisements