
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Finding number that appears for odd times - JavaScript
- Get count of how many times a string appears in a MySQL column?
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Return the element that appears for second most number of times in the array JavaScript
- MySQL query to count the number of times a specific integer appears in a column for its corresponding value in another column
- Count number of times value appears in particular column in MySQL?
- Program to find how many times a character appears in a string in PHP
- Take an array and find the one element that appears an odd number of times in JavaScript
- Repeating string for specific number of times using JavaScript
- First element that appears even number of times in an array in C++
- Counting how many times an item appears in a multidimensional array in JavaScript
- Count appearances of a string in another - JavaScript
- Return the index of first character that appears twice in a string in JavaScript
- Count how many times the substring appears in the larger String in Java
- How can I get the number of times a specific word appears in a column with MySQL?

Advertisements