Last active
February 27, 2017 13:09
-
-
Save ltpitt/ad53cfa7db8fd13f45df74b482ef5770 to your computer and use it in GitHub Desktop.
Javascript function that counts occurrencies of a substring in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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