0

Have tried this a few different ways and I've run into issues each time.

My initial approach:

function solve(a,b) {

var re = new RegExp(b,"g");
var res = a.match(re);
console.log(res);

}

solve("zaz","zazapulz") //returns null

And this approach as well:

function solve(a,b) {

String.prototype.count=function(c) { 
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
};

console.log(a.count(b)); 

}


solve("zaz","zazapulz") //returns 0
fromspace
  • 355
  • 3
  • 18

3 Answers3

4

Use split

function solve(a,b) {
   return b.split( a ).length - 1;
}

Demo

function solve(a, b) {
  return b.split(a).length - 1;
}

console.log(solve("zaz", "zazapulz"))

Note

  • Please note that this answer assumes that matches don't overlap.

If overlap also needs to be considered, then try this recursive method

var func = function( master, input, count )
{
    count = count || 0;
    var indexOf = master.indexOf( input );
    if ( indexOf == -1 )
    {
       return count;
    }
    else
    {
       return func( master.substring( indexOf + 1 ), input, ++count );     
    }
};
console.log( func( "zzz", "zz" ) );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

function solve(a,b) {

    var re = new RegExp(a,"g");  // ---+
                                 //    | switch variable a | b
    var res = b.match(re);       // ---+
    console.log(res);
}

solve("zaz","zazapulz")          // logs ["zaz"]
caramba
  • 21,963
  • 19
  • 86
  • 127
0

If you want to count matches including ones that overlap, you can iteratively use String.prototype.indexOf():

function solve (a, b) {
  var count = 0
  var from = 0
  
  while ((from = b.indexOf(a, from) + 1) !== 0) {
    count++
  }
  
  console.log(count)
}

solve('zaz', 'zazapulz')
solve('zaz', 'zazazaz')
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153