In PHP, it's pretty easy:
is_numeric(23);//true
is_numeric("23");//true
is_numeric(23.5);//true
is_numeric(true);//false
But how do I do this in Javascript? I could use a regular expression, but is there a function for this?
isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .
isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.
Use the RegExp. test() method to check if a string contains at least one number, e.g. /\d/. test(str) . The test method will return true if the string contains at least one number, otherwise false will be returned.
This checks for numerical values, including negative and floating point numbers.
function is_numeric(val){
return val && /^-?\d+(\.\d+)?$/.test(val + '');
}
@Vordreller: I corrected the Regex. It should work properly now.
function is_numeric(val) {
return ((+val) == val);
}
That should do the trick.
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