const countOccurrences = (text, str) => { let count = 0, i = 0, len = text.length - str.length; while (i <= len) { i = text.indexOf(str, i); if(!++i) break; count++; } return count; }; console.log(countOccurrences('ababa', 'aba'));