function occurrence(string,substring) {
var counter = 0;
var sub = substring.toLowerCase();
var str = string.toLowerCase();
var array = []
var ans;
for (var i = 0; i < str.length; i++) {
if (str.indexOf(sub) != -1) {
array[counter] = str.indexOf(sub);
counter += 1;
ans = array.length
alert(array); //tester to see inside array
} else {
ans = 0;
}
}
return ans
}
alert(occurrence("Party arty art","art")) //tester to see function in action
In the tester shown above, it should print out 3. But with my code, it prints out the length of the string. I'm trying to store the index of where "art" shows up in the string in an array so that I can print out the array to give the number of occurrences. However when I alerted the array inside the loop, it just prints out "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1".
Note: I'm trying to write this code with as few built in functions as possible. I'm new to javascript so some guidance will be much appreciated.
Also I'm trying to write this without .match()