I want to check if a string
contains only digits. I used this:
var isANumber = isNaN(theValue) === false; if (isANumber){ .. }
But realized that it also allows +
and -
. Basically, I want to make sure an input
contains ONLY digits and no other characters. Since +100
and -5
are both numbers, isNaN()
is not the right way to go. Perhaps a regexp is what I need? Any tips?
To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.
You can use the isdigit() macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.
To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.
The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.
how about
let isnum = /^\d+$/.test(val);
string.match(/^[0-9]+$/) != null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With