Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Created February 29, 2016 21:43
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 carlosascari/71227b0f366f38c602c6 to your computer and use it in GitHub Desktop.
Save carlosascari/71227b0f366f38c602c6 to your computer and use it in GitHub Desktop.
Count the occurrences of substring in a string.
/**
* Count the occurrences of substring in a string;
*
* @method occurrences
* @param haystack {String}
* @param needle {String}
* @param [allowOverlapping=false] {Boolean}
* @author Vitim.us http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
*/
function occurrences(haystack, needle, allowOverlapping) {
haystack = haystack + '', needle = needle + '';
if (needle.length <= 0)
{
return (haystack.length + 1);
}
var n = 0, pos = 0, step = allowOverlapping ? 1 : needle.length;
while (true)
{
pos = haystack.indexOf(needle, pos);
if (pos >= 0)
{
++n;
pos += step;
}
else
{
break;
}
}
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment