Table of Contents
Use for loop and CharCodeAt() method
grammar
step
Example
Use Number() constructor
Use regular expressions
Regular expression explanation
Home Web Front-end JS Tutorial How to check if a string contains only numbers in JavaScript?

How to check if a string contains only numbers in JavaScript?

Aug 27, 2023 pm 12:49 PM

JavaScript 中如何检查字符串是否只包含数字?

When we develop, we may need to find a string that only contains numbers and does not contain any other characters. The simplest way to check is to parse the number in the string and compare its length to the length of the original string. If both are the same, it means that the string contains only numbers. Users can use the parseInt() method to parse numbers in a string.

However, in this tutorial, we will learn other ways to check if a string contains only numbers in JavaScript.

Use for loop and CharCodeAt() method

We can use a for loop to traverse the string. We can get each character in the string using the index value and the charCodeAt() method to get its ASCII value. We can then compare the ASCII value of the character with the ASCII value of the number to find out whether the character is a number or a non-numeric character.

grammar

Users can follow the following syntax to check whether a string contains only numbers.

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;
}
Copy after login

In the above syntax, we execute the charCodeAt() method for each string character.

step

Step 1 - Use a for loop to iterate over the string.

Step 2 - Use the charCodeAt() method to get the ASCII value of the character located at the i-th index in the string

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

Step 4 - If the iteration of the for loop completes and the function does not find any non-numeric characters, it returns true, indicating that the string contains only digits.

Example

In the example below, we take two strings containing only numbers and mixed characters. The user can observe the output, which prints a message on the web page based on a string containing only numbers or non-numbers.

<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>
Copy after login

Use Number() constructor

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

We can also pass a numeric string as a parameter to the Number() constructor. It parses numbers and returns numeric values. If we pass a string containing non-numeric characters, it will return NaN value.

grammar

Users can use the following syntax to use Numberconstructor() to check if a string contains only numbers.

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

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

Example

In the example below, string1 contains only numbers. We pass it as an argument to the Number() constructor and the user can see that it returns the actual numeric value in the output instead of NaN.

<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>
Copy after login

Use regular expressions

In this section, we will create a regular expression that can be used to match non-numeric characters into a string. If we find any single match of a non-numeric character, we can say that the string contains non-numeric characters as well.

grammar

Users can use regular expressions according to the following syntax to check whether a string only contains numbers.

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

The above syntax uses the test() method to match the regular expression pattern with a string.

The test() method will return true if the string contains any non-numeric characters.

Regular expression explanation

  • \D - matches any single non-numeric character.

We can also use the "g" flag with a regular expression to match all occurrences of non-numeric characters, but it is enough for us to know that the string contains only one non-numeric character.

Example

In this example, when the user clicks the button, the isContainsDigits() function has a different string parameter. Additionally, users can observe the output of the test() method with 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>
Copy after login

We learned three different ways to check if a string contains only numbers. Users can use the Number() constructor to perform tasks through a linear code.

The above is the detailed content of How to check if a string contains only numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles