settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Count Occurrences in JavaScript - task

+1 vote

Write JavaScript function that counts how many times a string occurs in a given text. Overlapping strings are allowed.
The input comes as two string arguments:

  • The first element is the target string
  • The second element is the text in which to search for occurrences.


Examples:

Input:
'the', 'The quick brown fox jumps over the lay dog.'

Output:
1


Input:
'ma', 'Marine mammal training is the training and caring for marine life such as, dolphins, killer whales, sea lions, walruses, and other marine mammals. It is also a duty of the trainer to do mental and physical exercises to keep the animal healthy and happy.'

Output:
7

The output should be a number, printed on the console.

asked in JavaScript category by user ak47seo

1 Answer

0 votes

Here is my JavaScript code:

function repStr(whatStr, text) {
    let count = 0;
    let index = text.indexOf(whatStr);

    while (index > -1) {
        count++;
        index = text.indexOf(whatStr, index + 1);
    }
    console.log(count);
}

repStr('ma', 'Marine mammal training is the training and caring for marine life such as, dolphins, killer whales, sea lions, walruses, and other marine mammals. It is also a duty of the trainer to do mental and physical exercises to keep the animal healthy and happy.');

 

answered by user eiorgert
...