How to Count Occurrences of a Substring in a String in JavaScript

CodeyMaze
Sep 9, 2023

--

There are many approaches to count occurrences of a substring inside a string. In this post we will cover two approaches -

Methods

  • Using loop
  • Using Regular Expressions

Method 1 — Using Loop

We can use a loop to iterate through the string and count the number of occurrences of the substring.

Let’s try this out -

We used the indexOf() method to search for the first occurrence of the substring in the string.

If the indexOf() method finds an occurrence (i.e., it returns a non-negative value), increment the count variable and update currentIndex to the position just after the found occurrence.

Read more at: https://codeymaze.com/how-to-count-occurences-in-a-string-in-javascript/

Originally published at https://codeymaze.com on September 9, 2023.

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet