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 appearances of a string in another - JavaScript
We are required to write a JavaScript function that takes in two strings and returns the count of the number of times the first string appears in the second string
Let’s say our string is −
const main = 'This is the is main is string';
We have to find the appearance of the below string in the above “main” string −
const sub = 'is';
Let’s write the code for this function −
Example
const main = 'This is the is main is string';
const sub = 'is';
const countAppearances = (main, sub) => {
const regex = new RegExp(sub, "g");
let count = 0;
main.replace(regex, (a, b) => {
count++;
});
return count;
};
console.log(countAppearances(main, sub));
Output
Following is the output in the console −
4
Advertisements