1
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()

jellybean_232
  • 189
  • 1
  • 4
  • 16
  • Is string always broken up by spaces? I would then explode the string by spaces and test each word. – Twisty Nov 06 '13 at 21:03
  • This whole thing could be re-written to use a regular expression. Create a regular expression with a global scope and get the number of matches. http://www.w3schools.com/jsref/jsref_obj_regexp.asp – Brian Shamblen Nov 06 '13 at 21:05
  • Possible duplicate of http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string – megawac Nov 06 '13 at 21:06

3 Answers3

1

What about something like this?

function occurrence(string, substring) {
    var counter = 0;
    var sub = substring.toLowerCase();
    var str = string.toLowerCase(); 
    var array = [];
    var index = -1;

    do {
        index = str.indexOf(sub, index + 1);
        if (index != -1) {
            array[counter++] = index;
            i = index;
        }
    } while (index != -1);

    return counter; // or return array; if you want the indexes
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • @VonnieVoong Glad I could help. If this (or any other) answer resolved your issue, consider accepting the answer which most completely and correctly resolved your issue. This indicates to other users that the problem has been solved and it helps future visitors who've encountered a similar issue to know that the solution may help them as well. See [What does it mean when an answer is "accepted"?](http://stackoverflow.com/help/accepted-answer). Also, once you've earned 15 or reputation, you should upvote any answer you felt was useful and well-written. – p.s.w.g Nov 06 '13 at 21:36
0

Have you considered doing a regular expression match? That would probably be the best thing in this case.

Here you go: (PS, you might want to avoid using built in names like "string" and "integer" when naming variables)

you need to create a function to escape any regex characters from your string:...then use that function.

function occurrence(str, substr) {
  var escaped = escapeFn(substr)
  var regex = new RegExp(escaped,"g")

  return str.match(regex).length

}

EDIT: sorry, i must have missed at the bottom where you said you didn't want to use match.

deweyredman
  • 1,440
  • 1
  • 9
  • 12
0

Might want to use match():

Search a string for "ain":

var str = "The rain in SPAIN stays mainly in the plain"; 
var res = str.match(/ain/g);

The result of res will be an array with the values:

ain,ain,ain

So for your example, something like this might work:

function occurrence(string, substring) {
    var counter = 0;
    var sub = new RegExp(escapeRegexStringCharactersFunction(substring.toLowerCase()),"g");
    var str = string.toLowerCase(); 
    var array = []

    array = str.match(sub);
    counter = array.length;

    return counter;
}

Even simpler:

function occurrence(string, substring) { 
    var array = []
    var sub = new RegExp(escapeRegexStringCharactersFunction(substring),"gi");
    array = string.match(sub);
    return array.length;
}
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • That occurrence code won't work and would be pretty complicated (assuming you wanted to escape the regex from the substring). But you would need to do something along the lines of `var re = new RegExp( escapeRegexStringCharactersFunction(substring), "g")` – megawac Nov 06 '13 at 21:15
  • And `array` variable in the second example is created and then never used – megawac Nov 06 '13 at 21:16
  • Thanks @megawac, made changes to my examples. – Twisty Nov 06 '13 at 21:23
  • what if the substring contains some special regex characters such as a period. See http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – megawac Nov 06 '13 at 21:29