Count appearances of a string in another - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 14-Sep-2020 14:09:11
Advertisements