We would like to know how to recursively find a substring within a string.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function strCount(str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;<!--from w w w.j a v a 2 s .com-->
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen),sub);
} else
return strCount(str.substring(1),sub);
}
document.writeln(strCount("catdogcowcat","cat"));
</script>
</head>
<body>
</body>
</html>
The code above is rendered as follows: