Pure JavaScript: a Function Like jQuery's isNumeric()
Achieve jQuery's isNumeric()
precision with:
Confirms validity for both numbers and numeric strings:
Relies on Number.isFinite()
for direct numeric check and coerces strings for numeric string evaluation.
Why Not parseInt and What's the Deal with isNaN?
In this algorithm, parseInt('123px')
would return 123
, providing a false positive for a numeric check. To avoid this, we coerce the string to a number to verify its full conformity to a numeric structure, excluding any irrelevant characters.
A pitfall: isNaN()
accepts isNaN('123')
returning false (not NaN), conversely, Number.isNaN()
strictly returns true only for NaN. Here we use the more robust Number.isFinite()
which harmoniously marries the two.
Deciphering Decimal and Numeric Formats
To accurately handle decimal numbers and detect assorted numeric formats, the notorious exponential notation, our solution leverages parseFloat()
. Helping us parse and verify not just integers but floating points with exactitude.
Effective Standalone Implementation
The isNumeric
function morphs into a standalone validator. Thus, minimizing code by shedding the extra layer of jQuery, making the codebase lean and mean.
Handling the Weird and Wacky
Unusual suspects like Infinity
and NaN
,although numeric in principle, are expertly managed. Number.isFinite()
ensures, the check isn’t passed, and what you're seeing is indeed a real, absolute number, and not some mathematical chicanery that could scramble your calculations.
Regex Magic: Sharpening our Numeric Check
If you ever want to tighten up security in stringville, you can always count on regular expressions. We can eliminate malformed decimal numbers while accepting correct ones like:
Upgrade: From isNumeric method to Number.isNumeric
Give your JavaScript environment a touch of class with a built-in Number.isNumeric method. Just don't tell Douglas Crockford.
Tip: isNumeric
will recognize "numeric equivalents" like "123". This can prove beneficial for duck typing. Used thoughtfully, it empowers dynamically-typed Javascript but beware of unintended side effects!
Preventing false positives
While the temptation might be to use + '123'
for a quick check if a string is numeric, don't. It fails with empty strings (+ '' === 0
), and we don't want that.
Hexadecimal strings throw another curve. parseInt('0x10')
and parseFloat('0x10')
return different results. Stick to our function to exclude these tricky non-standard numeric representations.
References
Was this article helpful?