1function countOccurences(string, word) {
2 return string.split(word).length - 1;
3}
4var text="We went down to the stall, then down to the river.";
5var count=countOccurences(text,"down"); // 2
1/** Function that count occurrences of a substring in a string;
2 * @param {String} string The string
3 * @param {String} subString The sub string to search for
4 * @param {Boolean} [allowOverlapping] Optional. (Default:false)
5 *
6 * @author Vitim.us https://gist.github.com/victornpb/7736865
7 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
8 * @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
9 */
10function occurrences(string, subString, allowOverlapping) {
11
12 string += "";
13 subString += "";
14 if (subString.length <= 0) return (string.length + 1);
15
16 var n = 0,
17 pos = 0,
18 step = allowOverlapping ? 1 : subString.length;
19
20 while (true) {
21 pos = string.indexOf(subString, pos);
22 if (pos >= 0) {
23 ++n;
24 pos += step;
25 } else break;
26 }
27 return n;
28}