Home > Article > Web Front-end > 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.
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.
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 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.
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>
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.
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.
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>
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.
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.
\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.
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!