Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Count Appearances of a String in Another String in 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: 2020-09-14T14:09:11+05:30

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements