Created
February 29, 2016 21:43
-
-
Save carlosascari/71227b0f366f38c602c6 to your computer and use it in GitHub Desktop.
Count the occurrences of 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
/** | |
* 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