str1과 str2와 같은 두 개의 문자열을 받는 JavaScript 함수를 작성해야 합니다. 그런 다음 함수는 str2가 str1에 나타나는 횟수를 계산하고 반환해야 합니다.'
예를 들어 -
count('this is a string', 'is') should return 2; 예시
이에 대한 코드는 -
const str1 = 'this is a string';
const str2 = 'is';
const countOccurrences = (str1, str2, allowOverlapping = true) => {
str1 += "";
str2 += "";
if (str2.length <= 0) return (str1.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : str2.length;
while (true) {
pos = str1.indexOf(str2, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
};
console.log(countOccurrences(str1, str2)); 출력
콘솔의 출력은 -
2