• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / JavaScript / Using JavaScript to Count the Occurrences in a String

Using JavaScript to Count the Occurrences in a String

August 20, 2022 Leave a Comment

We can use JavaScript to count the occurrences of a char or number in a string by using the JavaScript match() method, the length property, and a regex expression.

someString.match(/c/gi).length;

Not that the formula above works great as long as the character or number is in the string. However, if it is not found in the string, the expressions will return an error. This is because someString.match(/c/gi) will return null if c is not found in the string, and you cannot use the length property of a null value.

To make sure our code always works, we can simply add an if-else statement to check for this.

var charOccurrences = string1.match(/c/gi);
if( charOccurrences != null ){
  charOccurrences = charOccurrences.length;
} else {
  charOccurrences = 0;  
}

Let’s see this in action with the following example.

var string1 = "How many times does c appear in this sentence?";
var numOfOccurrences = string1.match(/c/gi);
if( numOfOccurrences != null ){
  var numOfOccurrences = numOfOccurrences.length;
} else {
  var numOfOccurrences = 0;  
}

console.log(numOfOccurrences);

#Output
2

Count the Occurrences in a String Using JavaScript

In this example, we will let the user enter a string and a char or number they want to count the number of occurrences of.

First, we will set up some HTML that will let a user enter a string, and a value. Then we will use a function to count the number of times each value appears in the String.

Here is the HTML:

<div id="div1">
  <label for="string1">Enter a String:</label>
  <input type="text" id="string1" name="string1">
  <label for="string1">Enter a Char or Number to Count:</label>
  <input type="text" id="string2" name="string2">
  <div id="click-me" onclick="findOccurrences()">Find Occurrences</div>
  <b><div id="userString"></div></b>
  <div id="results2">Number of times <span id="userValue"></span> appears in the String above: <span id="numOccurrences"></span></div>

Below is a function that will get the count the occurrences of the user value in a given string. We will then post the results using the textContent property.

function findOccurrences(){
  //Get the string the user has entered
  var string = document.getElementById("string1").value;

  //Get value user has entered
  var val1 = document.getElementById("string2").value;

  //Count how many values are in the string
  var regex = new RegExp(val1,"gi");
  var count = string.match(regex);
  if( count != null ){
    count = count.length;
  } else {
    count = 0;  
  }

  //Post the number of occurrences for user to see
  document.getElementById("userString").textContent = string;
  document.getElementById("userValue").textContent = val1;
  document.getElementById("numOccurrences").textContent = count;
};

The final code and output for counting the number of occurrences in a String is below:

Code Output:




Find Occurrences

Number of times appears in the String above:

Full Code:

<div id="div1">
  <label for="string1">Enter a String:</label>
  <input type="text" id="string1" name="string1">
  <label for="string1">Enter a Char or Number to Count:</label>
  <input type="text" id="string2" name="string2">
  <div id="click-me" onclick="findOccurrences()">Find Occurrences</div>
  <b><div id="userString"></div></b>
  <div id="results2">Number of times <span id="userValue"></span> appears in the String above: <span id="numOccurrences"></span></div>

<script>

function findOccurrences(){
  var string = document.getElementById("string1").value;
  var val1 = document.getElementById("string2").value;
  var regex = new RegExp(val1,"gi");
  var count = string.match(regex);
  if( count != null ){
    count = count.length;
  } else {
    count = 0;  
  }
  document.getElementById("userString").textContent = string;
  document.getElementById("userValue").textContent = val1;
  document.getElementById("numOccurrences").textContent = count;
};

</script>

Count Occurrences in a String Using a For Loop

We can also easily count the occurrences of a number in a String using a loop and counting the number of occurrences we find in the String.

var string1 = "How 2many times2 the number 2 occurs in this sentence2?";
function countOccurrences(string){
  var theString = string.toLowerCase();
  var char;
  var count = 0;
  for ( var i = 0; i < theString.length; i++ ){
    char = theString.charAt(i);
    if (char == 2){
      count = count + 1;
    };
  };
  return count;
};

var numOfOccurrences = countOccurrences(string1);

The result of the above example (numOfOccurrences) would return 4, as the number 2 occurs 4 times in the sentence above.

Hopefully this article has been useful for you to learn how to use JavaScript to count the occurrences in string.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to Get Date Format in dd mm yyyy
  • 2.  Using JavaScript to Get the Page Title
  • 3.  JavaScript acos – Find Arccosine and Inverse Cosine of Number
  • 4.  JavaScript acosh – Find Hyperbolic Arccosine of Number
  • 5.  Using JavaScript to Check if Variable is a Function
  • 6.  JavaScript Capitalize First Letter of Every Word
  • 7.  Remove Special Characters From String in JavaScript
  • 8.  Using JavaScript to Increment a Variable by 1
  • 9.  How to Split a Number into Digits in JavaScript
  • 10.  Sum the Digits of a Number in JavaScript

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy