freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/count-occurrences-of-a-substring.english.md
Randell Dawson 04f18e43f6 fix(curriculum): Remove unnecessary assert message argument from English Coding Interview Prep challenges - 02 (#36412)
* fix: removed assert msg argument

* fix: removed msgs surrounded by 2 single quotes

* fix: removed missing 2 assert msg arguments

* fix: remove msg surrounded by two single quotes

* fix: removed unnecessary assert msg args

* fix; remove msgs surrounded by double quotes

* fix: removed unnecessary assert msg args

* fix: remove unnecessary assert msg args

* fix: removed unnecessary assert msg arg

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg arg

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg args

* fix: removed unnecessary assert msg arg

* fix: removed unnecessary assert msg args

* fix: Restore expected values to assertions

* fix: remove assertion message

Co-authored-by: Vivek Agrawal <vivekmittalagrawal@gmail.com>
2019-07-26 14:24:52 +02:00

2.0 KiB

title, id, challengeType
title id challengeType
Count occurrences of a substring 596fda99c69f779975a1b67d 5

Description

Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:
  • the first argument being the string to search, and
  • the second a substring to be searched for.
It should return an integer count. The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left.

Instructions

Tests

tests:
  - text: <code>countSubstring</code> is a function.
    testString: assert(typeof countSubstring === 'function');
  - text: <code>countSubstring("the three truths", "th")</code> should return <code>3</code>.
    testString: assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
  - text: <code>countSubstring("ababababab", "abab")</code> should return <code>2</code>.
    testString: assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
  - text: <code>countSubstring("abaabba*bbaba*bbab", "a*b")</code> should return <code>2</code>.
    testString: assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);

Challenge Seed

function countSubstring(str, subStr) {
  // Good luck!
  return true;
}

After Test

const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];

Solution

function countSubstring(str, subStr) {
  const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
  const matches = str.match(new RegExp(escapedSubStr, 'g'));
  return matches ? matches.length : 0;
}