Friday, 27 September 2013

Which is the safest way to discriminate 0 from empty string in JavaScript?

Which is the safest way to discriminate 0 from empty string in JavaScript?

From user input, I receive a string which must contain numbers. 0 and
empty string must be treated differently.
I've made this brief case study
0 == "" // true
parseInt(0) == "" // true
parseInt("") // NaN
parseInt("") == "NaN" // false
parseInt("") == NaN // false
typeof parseInt("") // "number"
With a bit of extra research I've made up this solution (considering
uInput the user input)
function userInput(uInput){
var n = parseInt(uInput);
if (isNan(n))
// empty string
else
// 0 or number
}
It looks like it is able to distinguish 0 from empty string correctly in
Google Chrome.
What I'd like to know is:
Is this the best/most efficient solution?
Is this solution compatible in any browser?
Is this even a solution at all? Is there any way n can become something
other than a number (considering uInput could be any kind of string)?
I wouldn't be asking this, but since empty string can become 0 (?!) I
don't know to which kind of holes I'm exposed.

No comments:

Post a Comment