Advertisement
Guest User

Untitled

a guest
May 28th, 2015
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. /** Function count the occurrences of substring in a string;
  2. * @param {String} string Required. The string;
  3. * @param {String} subString Required. The string to search for;
  4. * @param {Boolean} allowOverlapping Optional. Default: false;
  5. */
  6. function occurrences(string, subString, allowOverlapping) {
  7. string += "";
  8. subString += "";
  9. if (subString.length <= 0) return string.length + 1;
  10.  
  11. var n = 0, pos = 0;
  12. var step = (allowOverlapping) ? (1):(subString.length);
  13.  
  14. while (true) {
  15. pos = string.indexOf(subString, pos);
  16. if (pos >= 0) {
  17. n++;
  18. pos += step;
  19. } else break;
  20. }
  21. return(n);
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement