Skip to content

Instantly share code, notes, and snippets.

@victornpb
Last active June 7, 2023 14:37
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victornpb/7736865 to your computer and use it in GitHub Desktop.
Save victornpb/7736865 to your computer and use it in GitHub Desktop.
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
Copy link

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

@earth-the-home
Copy link

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

@Akashkmr938
Copy link

occurrences("This is very good", "", true) will give 18 which seems incorrect.

why this condition if (subString.length <= 0) return (string.length + 1);

@VinnyStuff
Copy link

VinnyStuff commented Apr 20, 2021

occurrences("This is very good", "", true) will give 18 which seems incorrect.

why this condition if (subString.length <= 0) return (string.length + 1);

This is to prevent occurrences("asfsdfasdfasd", "") from looping infinitely.

It returns length+1 because:

> "abcd".match(new RegExp('', 'g'))
// ["", "", "", "", ""] (5)

@eyssette
Copy link

Thanks for this! I would like to use your function in an open-source project. What is the license of your code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment