How to Count String Occurrence in String in JavaScript

JavaScript is a versatile and dynamic programming language that is widely used to create interactive and dynamic websites.

As a beginner in JavaScript, you may encounter tasks that require you to count the occurrence of a specific string in another string.

This tutorial will show you how to count string occurrences in JavaScript with several code examples and explanations.


Using for Loop

The simplest way to count string occurrences in JavaScript is by using a for loop.

You loop through the original string and compare each character with the target string.

When a match is found, you increment a counter variable.

Here is an example:

function countString(target, original) {
  let count = 0;
  for (let i = 0; i < original.length; i++) {
    if (original.substring(i, i + target.length) === target) {
      count++;
      i += target.length - 1;
    }
  }
  return count;
}

Using split Method

Another way to count string occurrences in JavaScript is by using the split method.

The split method converts a string into an array of substrings, and the length of the array will give you the number of occurrences.

Here is an example:

function countString(target, original) {
  return original.split(target).length - 1;
}

Using replace Method

A third way to count string occurrences in JavaScript is by using the replace method.

The replace method replaces a target string with another string, and you can use this method to count occurrences by replacing the target string with an empty string.

Here is an example:

function countString(target, original) {
  return original.split(target).length - 1;
}

Conclusion

In this tutorial, we have shown you three methods to count string occurrences in JavaScript.

Whether you’re a beginner or an experienced developer, these methods should help you count string occurrences in your JavaScript code.

We hope you found this tutorial helpful, and if you have any questions or comments, please let us know in the comments section below.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.