Найти количество вхождений подстроки в строку
На выходе хочу получить:
console.log(countOccurrences('abefhiefj', 'ef')); // 2 Мой код: const countOccurrences = (text, str) => { if (str === '') { return null; } let counter = 0; for (let char of text) { if (char === str) { counter++; } } return counter; }; Но он работает если вторым параметром будет только один символ, например: console.log(countOccurrences('abefhiefj', 'e')); Но что добавить в коде чтобы искало кол-во вхождений в переданном параметре с более чем в один символ? |
NovichokJS,
разрежьте строку по образцу и верните длину массива. |
Цитата:
|
во втором передаваемом параметре функции может быть и больше чем 2 символа
|
NovichokJS,
const countOccurrences = (text, str) => { let {length} = text.split(str); return --length; }; console.log(countOccurrences('abefhiefj', 'ef')); |
Цитата:
|
Цитата:
let length = text.split(str).length; |
NovichokJS,
Деструктурирующее присваивание |
Цитата:
Цитата:
|
И тут пришел поручик, и все опошлил
countOccurrences('ababa', 'aba'));// ??? |
Gvozd,
:lol: |
:) :write:
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')); |
:-?
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')); |
countOccurrences('aaa', 'aa');//??? |
Gvozd,
исправил))) |
Часовой пояс GMT +3, время: 21:33. |