

- 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
Common Character Count in Strings in JavaScript
We are required to write a JavaScript function that takes in two strings, let us say str1 and str2.
The function should count the number of common characters that exist in the strings.
For example −
const str1 = 'aabbcc'; const str2 = 'adcaa';
Then the output should be 3
Example
Following is the code −
const str1 = 'aabbcc'; const str2 = 'adcaa'; const commonCharacterCount = (str1 = '', str2 = '') => { let count = 0; str1 = str1.split(''); str2 = str2.split(''); str1.forEach(e => { if (str2.includes(e)) { count++; str2.splice(str2.indexOf(e), 1); }; }); return count; }; console.log(commonCharacterCount(str1, str2));
Output
Following is the output on console −
3
- Related Questions & Answers
- Count common characters in two strings in C++
- Count common subsequence in two strings in C++
- Count the number of common divisors of the given strings in C++
- Common Words in Two Strings in Python
- Function to check two strings and return common words in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Greatest Common Divisor of Strings in Python
- Common words among tuple strings in Python
- Count of sub-strings that contain character X at least once in C++
- Print common characters of two Strings in alphabetical order in C++
- Formatted Strings Using Template Strings in JavaScript
- Template strings in JavaScript.
- Count common prime factors of two numbers in C++
- Python – Sort by Rear Character in Strings List
- Python program to remove words that are common in two Strings
Advertisements