Skip to content

Instantly share code, notes, and snippets.

@ltpitt
Last active February 27, 2017 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ltpitt/ad53cfa7db8fd13f45df74b482ef5770 to your computer and use it in GitHub Desktop.
Save ltpitt/ad53cfa7db8fd13f45df74b482ef5770 to your computer and use it in GitHub Desktop.
Javascript function that counts occurrencies of a substring in a string
/** Function that counts occurrencies 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)
* @return {Integer} Total count of occurrencies
*/
function occurrencesCount(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;
}
// Here's a few simple examples
occurrencesCount("foofoofoo", "bar"); // Will return 0
occurrencesCount("foofoofoo", "foo"); // Will return 3
occurrencesCount("foofoofoo", "foofoo"); // Will return 1
// Here's an example with allowOverlapping set to true
occurrencesCount("foofoofoo", "foofoo", true); // Will return 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment