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

Updated on: 14-Sep-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements