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

AI Hentai Generator
Generate AI Hentai for free.

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



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

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

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion
