To check whether a given input is a number, which of the following approaches are more efficient?
!isNaN(input)
OR using regex,
var regex=/^[0-9]+$/;
(x.match(regex))
P.S I’m ignoring empty string ("") for now which will return true for !isNaN("")
2
Answers
if you SIMPLY want to check whether a given input is a number
then i think using ‘isNan()’ would suffice
it works for both integer numbers as well as decimals.
// emphasis on ‘SIMPLY’
There’s a little impact on performance in both cases unless you want to parse a million strings or so. However here is a little benchmark parsing 1 mio. strings per solution. Could be improved of course. In my case (Chromium on KUbuntu)
!isNaN()
is faster.