как подсчитать количество вхождений подстроки в строку на javascript — Q&A Хекслет
2026-02-26 19:00 Diff

Для подсчёта количества вхождений подстроки в строку на JavaScript можно воспользоваться различными подходами. Вот несколько возможных способов решения этой задачи:

С использованием метода split() и length:

const countOccurrences = (str, substr) => str.split(substr).length - 1; const mainStr = "abacabadabacaba"; const subStr = "aba"; const occurrences = countOccurrences(mainStr, subStr); console.log(occurrences); // Output: 3

С использованием регулярных выражений:

const countOccurrences = (str, substr) => { const regExp = new RegExp(substr, "g"); return (str.match(regExp) || []).length; } const mainStr = "abacabadabacaba"; const subStr = "aba"; const occurrences = countOccurrences(mainStr, subStr); console.log(occurrences); // Output: 3

Используя рекурсивную функцию:

const countOccurrences = (str, substr, count = 0) => { const index = str.indexOf(substr); if (index !== -1) { return countOccurrences(str.slice(index + substr.length), substr, count + 1); } return count; } const mainStr = "abacabadabacaba"; const subStr = "aba"; const occurrences = countOccurrences(mainStr, subStr); console.log(occurrences); // Output: 3

Выбор метода зависит от требований к производительности и структуре задачи. К примеру, использование регулярных выражений может быть более удобным, но в случае больших объемов данных может быть менее эффективным.