Skip to content

Instantly share code, notes, and snippets.

@victornpb victornpb/occurrences.js
Last active Apr 14, 2018

Embed
What would you like to do?
Function count the occurrences of substring in a string
/** Function that count occurrences of a substring in a string;
* @param {String} string The string
* @param {String} subString The sub string to search for
* @param {Boolean} [allowOverlapping] Optional. (Default:false)
*
* @author Vitim.us https://gist.github.com/victornpb/7736865/edit
* @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
* @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
*/
function occurrences(string, subString, allowOverlapping) {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
}
@thornedlove

This comment has been minimized.

Copy link

commented Jan 17, 2017

Thanks, I'm using your function in a php page.
I've included the url back to here.
Nice, clean, efficient code.
Well done!

@naveento

This comment has been minimized.

Copy link

commented Apr 14, 2018

how about "foofoofooooofo".split("foo").length

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.