0 added
0 removed
Original
2026-01-01
Modified
2026-02-26
1
<p>Для подсчёта количества вхождений подстроки в строку на JavaScript можно воспользоваться различными подходами. Вот несколько возможных способов решения этой задачи:</p>
1
<p>Для подсчёта количества вхождений подстроки в строку на JavaScript можно воспользоваться различными подходами. Вот несколько возможных способов решения этой задачи:</p>
2
<p>С использованием метода split() и length:</p>
2
<p>С использованием метода split() и length:</p>
3
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<p>С использованием регулярных выражений:</p>
3
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<p>С использованием регулярных выражений:</p>
4
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<p>Используя рекурсивную функцию:</p>
4
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<p>Используя рекурсивную функцию:</p>
5
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<p>Выбор метода зависит от требований к производительности и структуре задачи. К примеру, использование регулярных выражений может быть более удобным, но в случае больших объемов данных может быть менее эффективным.</p>
5
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<p>Выбор метода зависит от требований к производительности и структуре задачи. К примеру, использование регулярных выражений может быть более удобным, но в случае больших объемов данных может быть менее эффективным.</p>