- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to count the occurrence of a specific string in a string in JavaScript
We are required to write a JavaScript function that takes in two strings, say str1 and str2. The function should then count and return the number of times str2 appears in str1'
For example −
count('this is a string', 'is') should return 2;
Example
The code for this will be −
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));
Output
And the output in the console will be −
2
- Related Articles
- String function to replace nth occurrence of a character in a string JavaScript
- Java program to count the occurrence of each character in a string using Hashmap
- Create a polyfill to replace nth occurrence of a string JavaScript
- How to get the last index of an occurrence of the specified value in a string in JavaScript?
- How to get the first index of an occurrence of the specified value in a string in JavaScript?
- How to count the number of occurrences of a character in a string in JavaScript?
- How to count a number of words in given string in JavaScript?
- How to find the nth occurrence of substring in a string in Python?
- How to get the maximum count of repeated letters in a string? JavaScript
- Count appearances of a string in another - JavaScript
- How to replace the last occurrence of an expression in a string in Python?
- Count total punctuations in a string - JavaScript
- Removing a specific substring from a string in JavaScript
- How to find index of last occurrence of a substring in a string in Python?
- Finding the last occurrence of a character in a String in Java

Advertisements