How to check if a string contains only numbers in 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; }
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>
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. }
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>
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 }
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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...

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.

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.

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.

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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. �...
