How To Count The Number Of Digits In A String In JavaScript

Count the Number of Digits in a String in JavaScript

Today we will discuss how to count the number of digits in a String in JavaScript. We have 2 methods: replace() function and the For Loop method. Let’s check it out!

How to count the number of digits in a String in JavaScript

There are many ways to count the number of digits, but I will give you the most straightforward methods. And now we will find out together.

Using the replace() method

The replace() method finds the string for a specific value or a regex and returns a new string with all the number of digits found in the string. Then, we can use the length attributed to count the number in this new string.

Syntax:

string.replace(searchValue, newValue).length

Parameters:

  • searchValue: It is the value or expression which is replaced by the new value.
  • newValue: It is the value which replaces the search value.

Return: the amount of digits in the string.

Code example:

//  Initialize a variable stores string
var caseString1 = "3Learn2Share423.8<asd4b341ba2/2>3IT";

// Return amount of digits in the string and print
var countNumber1 = caseString1.replace(/\D/g, "").length;
console.log("amount of digits in the string is: " + countNumber1);

//  Initialize a variable stores string
var caseString2 = "3Learn  2   Share  @ 4 5$ 3IT";

// Return amount of digits in the string and print
var countNumber2 = caseString2.replace(/\D/g, "").length;
console.log("amount of digits in the string is: " + countNumber2);

Output:

amount of digits in the string is: 13
amount of digits in the string is: 5

Using the For Loop

In this method, we will use For loop to count the number of digits in the string. Firstly, we initialize a variable count with 0 value, which is used to store the number of digits in the string. Secondly, we use the loop to run for the entire string length, taking each character in the string to check if it is a number by the isNaN method. If it is a number, you need to increase the variable count by 1; else, you will pass. Follow the code example below.

Code example:

function countNumberOfDigits(str) {
	// Initialize variable used for storage
	var count = 0;

	// Use for loop check if the number is added to the variable res
	for (let i = 0; i < str.length; i++) {
		if (!isNaN(str[i])) {
			count += 1;
		}
	}

	return count;
}

var string = "3Learn2Share423.8<asd4b341ba2/2>3IT";
var res = countNumberOfDigits(string);
console.log("amount of digits in the string is: " + res);

Output:

amount of digits in the string is: 13

Summary

That’s all for today. We hope the ways to count the number of digits in a string in JavaScript that we mentioned above are helpful to you. If you have any questions, don’t forget to leave a comment below. Have a nice day!

Maybe you are interested:

Leave a Reply

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