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 the input value to first be interpreted as a number for the boolean compare. If that interpretation fails, the expression will result in NaN
. Then this numeric result is compared to the original, unaltered value you passed in. If they are the same, we have a winner. The check on the length is of course for the empty string special case. So in other words, 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.