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