Number of times a string appears 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 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
raja
Published on 14-Oct-2020 08:06:06
Advertisements