w3resource

JavaScript: Count the occurrence of a substring in a string

JavaScript String: Exercise-18 with Solution

Write a JavaScript function to count the occurrence of a substring in a string.

Test Data:
console.log(count("The quick brown fox jumps over the lazy dog", 'the'));
Output:
2
console.log(count("The quick brown fox jumps over the lazy dog", 'fox',false));
Output:
1

Pictorial Presentation:

JavaScript: Count the occurrence of a substring in a string

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Write a JavaScript function to count the occurrence of a substring in a string.</title>
</head>
<body>
</body>
</html>

JavaScript Code:

function count(main_str, sub_str) 
    {
    main_str += '';
    sub_str += '';

    if (sub_str.length <= 0) 
    {
        return main_str.length + 1;
    }

       subStr = sub_str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
       return (main_str.match(new RegExp(subStr, 'gi')) || []).length;
    }
 
console.log(count("The quick brown fox jumps over the lazy dog", 'the'));
console.log(count("The quick brown fox jumps over the lazy dog", 'fox',false));

Sample Output:

2
1

Flowchart:

Flowchart: JavaScript- Count the occurrence of a substring in a string

Live Demo:

See the Pen JavaScript Count the occurrence of a substring in a string - string-ex-18 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to chop a string into chunks of a given length.
Next: Write a JavaScript function to escape a HTML string.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts