How to check if the string contains only digits in JavaScript?


We may require to find the string, which contains only digits but not any other characters while developing. The easiest way to check can parse the numbers from the string and compare its length with the original string’s length. If both are the same, that means the string contains only digits. Users can use the parseInt() method to parse the numbers from the string.

However, in this tutorial, we will learn other methods to check if the string contains only digits in JavaScript.

Use the for-loop and CharCodeAt() method

We can iterate through the string using the for-loop. We can get every character from the string using its index value and the charCodeAt() method to get its ASCII value. After that, we can compare the character’s ASCII value with the digits' ASCII value and get the result that the character is a digit or non-digit character.

Syntax

Users can follow the syntax below to check if the string contains only digits.

function isOnlyDigits(string) {
   for (let i = 0; i < string.length; i++) {
      var ascii = string.charCodeAt(i);
      if (ascii < 48 || ascii > 57) {
         return false;
      }
   }
   return true;
}

In the above syntax, we are executing the charCodeAt() method for every string character.

Steps

Step 1 − Use the for-loop to iterate through the string.

Step 2 − Use the charCodeAt() method to get the ASCII value of the character, which is at the ith index in the string

Step 3 − Check if the ASCII value of the character at index ith is between 48 and 57. If not, that means it is a non-digits character and returns false.

Step 4 − If the iteration of the for-loop completes, and the function doesn’t find any nondigit character, return true, saying the string contains only digits.

Example

In the example below, we take two strings containing only digits and mix-characters. Users can observe the output, that it prints the message on the web page according to the string containing only digits or non-digits.

<html>
<body>
   <h3>Using the <i> for-loop and charCodeAt() </i> method to check if string contains only digits</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      function isOnlyDigits(string) {
         for (let i = 0; i < string.length; i++) {
            var ascii = string.charCodeAt(i);
            if (ascii < 48 || ascii > 57) {
               output.innerHTML += "The " + string + " contains non-digits characters also. <br/>";
               return false;
            }
         }
         output.innerHTML += "The " + string + " contains only digits characters also. <br/>";
         return true;
      }
      isOnlyDigits("122135567343");
      isOnlyDigits("df32d23");
   </script>
</body>
</html>

Use the Number() Constructor

In JavaScript, a Number is an object, and we can use its constructor to create its instance. We can pass a value as an argument of the Number() constructor to initialize the variable with the number value.

We can also pass the string of digits as an argument of the Number() constructor. It parses the number and returns the number value. If we pass the string containing the non-digit characters, it returns the NaN value.

Syntax

Users can use the syntax below to use the Number constructor() to check if the string contains only digits.

let num = Number(string1);
if (num != NaN) {
  
  // contains non-digit numbers
}else{
   
   // contains only digits.
}

In the above syntax, string1 is a string containing digits and non-digits characters. If the Number() constructor returns NaN, the string contains non-digits characters; Otherwise, it returns the number value.

Example

In the example below, the string1 contains only the digits. We have passed it as an argument of the Number() constructor, and users can see that it returns the actual number value rather than NaN in the output.

<html>
<body>
    <h3>Using the <i> Number() constructor </i> method to check if string contains only digits</h2>
    <div id="output"></div>
    <script>
      let output = document.getElementById("output");
      let string1 = "3433454646";
      let num = Number(string1);
      if (num != NaN) {
         output.innerHTML += "The " + string1 + " Contains only digits! <br/>";
      } else {
         output.innerHTML += "The " + string1 + " Contains non-digits characters! <br/>";
      }
      </script>
</body>
</html>

Use the Regular Expression

In this section, we will create a regular expression that we can use to match a non-digit character into the string. If we find any single match of non-digit characters, we can say that string contains the non-digits characters also.

Syntax

Users can follow the syntax below to use the regular expression to check if string contains only digits.

let regex = /\D/;
let bool = regex.test(str);
if (bool) {
   
   // contains non-digits 
} else {
   
   // contains only digits
}

The test() method is used in the above syntax to match the regex pattern with the sting.

The test() method returns true if the string contains any non-digit character.

Regex Explanation

  • \D − It is used to match any single non-digit character.

We can also use the ‘g’ flag with the regular expression to match all occurrences of nondigit characters, but we have enough to know that string contains only a single non-digit character.

Example

In this example, the isContainsDigits() function with different string arguments when the user clicks on the button. Furthermore, users can observe the output of the test() method with the different strings.

<html>
<body>
   <h3>Using the <i> regular expression </i> method to check if string contains only digits </h3>
   <div id = "output"> </div>
   <button onclick="isContainsDigits('8954656');isContainsDigits('dfjsdh4354354')">
      Click here
   </button>
   <script>
      let output = document.getElementById("output");
      let regex = /\D/;
      function isContainsDigits(str) {
         let bool = regex.test(str);
         if (bool) {
            output.innerHTML += "The " + str + " Contains non-digits! <br/>";
         } else {
            output.innerHTML += "The " + str + " Contains only digits characters! <br/>";
         }
      }
   </script>
</body>
</html>

We learned three different approaches to checking if the string contains only digits. Users can use the Number() constructor to perform the task with one linear code.

Updated on: 10-Mar-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements