Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of times a string appears in another JavaScript
We are required to write a JavaScript function that takes in two strings and returns the count of the number of times the str1 appears in the str2.
Example
The code for this will be −
const main = 'This is the is main is string';
const sub = 'is';
const countAppearances = (main, sub) => {
const regex = new RegExp(sub, "g");
let count = 0;
main.replace(regex, (a, b) => {
count++;
});
return count;
};
console.log(countAppearances(main, sub));
Output
The output in the console −
4
Advertisements