Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - How To Count String Occurrence in String?
Next article icon

JavaScript - How To Count String Occurrence in String?

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various methods to count string occurrence in a string using JavaScript.

1. Using match() Method (Common Approach)

The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the array gives the count.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; const count = (s1.match(new RegExp(s2, "g")) || []).length; console.log(count);  

Output
2 
  • new RegExp(word, "g"): Creates a global regular expression for the target word.
  • match(): Returns an array of matches.
  • || []: Handles cases where no matches are found (returns an empty array).

2. Using while Loop

You can manually iterate through the string to count occurrences by checking for the substring at each position.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; let count = 0; let pos = 0;  while ((pos = s1.indexOf(s2, pos)) !== -1) {     count++;     // Move past the current match     pos += s2.length;  } console.log(count); 

Output
2 
  • indexOf(s2, pos): Finds the position of the substring starting from pos.
  • pos += s2.length: Advances the position to avoid counting overlapping matches.

3. Using split() Function

By splitting the string at each occurrence of the target substring, the resulting array.length-1 will give the count.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; const count = s1.split(s2).length - 1; console.log(count); 

Output
2 
  • split(word): Splits the string at every occurrence of the substring.
  • length - 1: The number of occurrences equals the number of splits minus one.

4. Using indexOf() in a Loop

Another approach using indexOf() involves repeatedly searching for the substring.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; let count = 0; let pos = s1.indexOf(s2);  while (pos !== -1) {     count++;     pos = s1.indexOf(s2, pos + s2.length); } console.log(count);  

Output
2 
  • indexOf(word, start): Finds the substring starting from the specified index.
  • The loop continues until indexOf() returns -1 (no more matches).

5. Using Regular Expressions

Regular expressions offer a concise and powerful way to count substring occurrences.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; const regex = new RegExp(s2, "g"); const count = (s1.match(regex) || []).length; console.log(count); 

Output
2 
  • RegExp(word, "g"): Enables global matching of the substring.
  • match(): Returns all matches as an array.

6. Using reduce() Method

You can use reduce() to iterate through an array representation of the string (e.g., split by spaces) and count matches.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; const count = s1.split(" ")     .reduce((acc, curr) =>          (curr === s2 ? acc + 1 : acc), 0); console.log(count); 

Output
2 
  • split(" "): Breaks the string into an array of words.
  • reduce(): Accumulates the count by comparing each element with the target word.

7. Using includes() and slice() Methods

You can use includes() to check for the substring and slice() to move past each match.

JavaScript
const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; let count = 0; let temp = s1;  while (temp.includes(s2)) {     count++;     temp = temp.slice(temp.indexOf(s2) + s2.length); } console.log(count); 

Output
2 
  • includes(word): Checks if the substring exists in the string.
  • slice(): Creates a new substring starting after the current match.

Which Method To Choose?

  • The match() method with a global regular expression is the most efficient and widely used method for counting substring occurrences.
  • For specific cases, such as overlapping matches or advanced patterns, regular expressions provide flexibility.
  • Approaches like split() and loops with indexOf() are clear and concise alternatives, especially for simple substring counting. Choose the method that best fits your needs based on the input and complexity!

Next Article
JavaScript - How To Count String Occurrence in String?

B

bestharadhakrishna
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

    JavaScript - How to Count Words of a String?
    Here are the various methods to count words of a string in JavaScript.1. Using split() MethodThe simplest and most common approach is to use the split() method to divide the string into an array of words and count the length of the array.JavaScriptconst count = (s) => s.trim().split(/\s+/).length
    3 min read
    PHP Find the number of sub-string occurrences
    We are given two strings s1 and s2. We need to find the number of occurrences of s2 in s1. Examples: Input : $s1 = "geeksforgeeks", $s2 = "geeks" Output : 2 Explanation : s2 appears 2 times in s1 Input : $s1 = "Hello Shubham. how are you?"; $s2 = "shubham" Output : 0 Explanation : Note the first let
    2 min read
    CSES solution - Counting Patterns
    Given a string S and patterns[], count for each pattern the number of positions where it appears in the string. Examples: Input: S = "aybabtu", patterns[] = {"bab", "abc", "a"}Output: 102Explanation: "bab" occurs only 1 time in "aybabtu", that is from S[2...4]."bab" does not occur in "aybabtu"."a" o
    15 min read
    PHP substr_count() Function
    The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., "abc" substring is not present in
    3 min read
    PHP mb_substr_count() Function
    The  mb_substr_count() function is an inbuilt function in PHP that counts the occurrence of strings within a given string. Syntax: mb_substr_count($haystack, $needle, $encoding): intParameters: This function accepts three parameters that are described below: $haystack:  This is the main parameter wh
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences