What I want to do is determine if the string is numeric. I would like to know what people think of the two solutions that I am trying to solve between (OR, if there is a better solution that I have not found yet). The parseInt function is not suitable because it will return an integer value for a parameter of type "40 years". Two solutions that I decide between:
Use Integer.valueOf () with try catch
function isNumeric(quantity)
{
var isNumeric = true
try
{
Integer.valueOf(quantity)
}
catch(err)
{
isNumeric = false
}
return isNumeric
}
Or check each character separately
function IsNumeric(quantity)
{
var validChars = "0123456789";
var isNumber = true;
var nextChar;
for (i = 0; i < quantity.length && isNumber == true; i++)
{
nexChar = quantity.charAt(i);
if (validChars.indexOf(nextChar) == -1)
{
isNumber = false;
}
}
return IsNumber;
}
I would have thought that there would be a simpler solution than both of them. Did I miss something?
NOTE. I use jQuery aswel, so if there is a jQuery solution that would be enough
source
share