Counting Number of Digits in a String in JavaScript

In this section we will see how to count the number of digits.

Using Regular Expressions

Use the regular expression to locate the digits.

Detailed Procedures
1. The first thing is to create a string , store digits and characters into it
2.The very next step is to use regular expression and locate each digit in the string.
3. The last step is count the total occurrences of the digits and to print it.

Example Program

Here is the example code which uses regular expression to count the occurrences

// Step 1: Define a string which consists of digits
let string = "Hello 4567, the address mentioned is 123, towards west of this road";

// Step 2: Use regular expression
let digit = str.match(/\d/g);

// Step 3: Count the number of matches
let digCount = digit ? digit.length : 0;

// Step 4: Log the result to the console
console.log("Number of digits in the string:", digCount);

Making Use of Looping

A different method of counting digits is to iterate through the string’s characters, determining whether or not each one is a digit.

Detailed Procedures
1. Over here, the first step is similar to that of the first step in the regular expression.
2. Initialize a count variable.
3. Use the for loop and travel through the string.
4. If the digit is found in the string, then increment the count variable.

Example Program

The example code using loops to find the count

// Step 1: Define a string that contains digits
let string = "Hello 4567, the address mentioned is 123, towards the west of this road";

// Step 2: Initialize a counter
let digCount = 0;

// Step 3: Loop through each character in the string
for (let i = 0; i < string.length; i++) {
    // Check if the character is a digit
    if (string[i] >= '0' && string[i] <= '9') {
        // Step 4: Increment the counter
        digCount++;
    }
}

// Step 5: Log the result to the console
console.log("Number of digits in the string:", digCount);

Output

Number of digits in the string: 7

Leave a Comment

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

Scroll to Top