Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regex.
If you can't use isNaN()
, this should work much better:
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
The (input - 0)
expression forces javascript to do type coercion on your input value; it must first be interpreted as a number for the boolean compare. If that conversion to a number fails, the expression will result in NaN
. Then this numeric result is compared to the original value you passed in. Since the left hand side is a number, type coercion is again used. They should always be the same (always true), but there's a special rule that says NaN
is never equal to NaN
, and so a value that can't be converted to a number will always return false. The check on the length is of course for the empty string special case. In summary, if you want to know if a value can be converted to a number, actually try to convert it to a number.
Note that it falls down on your 0x89f test, but that's because in many environments that's an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that's your reason for not using isNaN() then just wrap your own function around isNaN() that can also do the additional check.