Skip to content

Instantly share code, notes, and snippets.



Last active Mar 15, 2020
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
* @see Unit Test
* @see
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) {
pos += step;
} else break;
return n;

This comment has been minimized.

Copy link

@thornedlove thornedlove 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!


This comment has been minimized.

Copy link

@earth-the-home earth-the-home 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.