freeCodeCamp Challenge Guide: Count occurrences of a substring

Count occurrences of a substring


Solutions

Solution 1 (Click to Show/Hide)
function countSubstring(str, subStr) {
  let i = 0;
  let count = 0;
  const subStrLen = subStr.length;
  const upperBound = str.length - subStrLen;
  while (i < upperBound) {
    if (str.substr(i, subStrLen) === subStr) {
      count++;
      i += subStrLen;
    } else {
      i++;
    }
  }
  return count;
}
Solution 2 (Click to Show/Hide)
function countSubstring(str, subStr) {
  return (str.length - str.replaceAll(subStr, "").length) / subStr.length;
}
2 Likes