Number of times a string appears 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 str1 appears in the str2.

Example

The code for this will be −

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

The output in the console −

4

Updated on: 14-Oct-2020

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements