Last active
June 7, 2023 14:37
-
-
Save victornpb/7736865 to your computer and use it in GitHub Desktop.
Function 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
/** 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; | |
} |
how about "foofoofooooofo".split("foo").length
occurrences("This is very good", "", true) will give 18 which seems incorrect.
why this condition if (subString.length <= 0) return (string.length + 1);
occurrences("This is very good", "", true) will give 18 which seems incorrect.
why this condition
if (subString.length <= 0) return (string.length + 1);
This is to prevent occurrences("asfsdfasdfasd", "")
from looping infinitely.
It returns length+1 because:
> "abcd".match(new RegExp('', 'g'))
// ["", "", "", "", ""] (5)
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
Thanks, I'm using your function in a php page.
I've included the url back to here.
Nice, clean, efficient code.
Well done!