I'm trying to write a recursive program to count the number of times a substring ("cat") appears in a string ("catdogcowcat"). Not sure what I'm doing wrong, but I keep getting the following error:
TypeError: Cannot read property 'length' of undefined
Here's my code:
function strCount (str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen));
} else return strCount(str.substring(1));
}
I think it's breaking when I try to get the length of the substring on this line, but that's just my guess based on my infantile understanding of devtools debugging:
return 1 + strCount(str.substring(subLen));
Thanks!