Skip to content

Instantly share code, notes, and snippets.

@victornpb
Last active June 7, 2023 14:37
Show Gist options
  • 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;
}
@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