I want to coerce strings to primitives whenever possible, in a way that is safe to pass any value. I'm looking for a more "native" way of doing it, instead of trying to cover all possible cases.
value("0") //0
value("1") //1
value("-1") //-1
value("3.14") //3.14
value("0x2") //2
value("1e+99") //1e+99
value("true") //true
value("false") //false
value("null") //null
value("NaN") //NaN
value("undefined") //undefined
value("Infinity") //Infinity
value("-Infinity") //-Infinity
value("") //""
value(" ") //" "
value("foo") //"foo"
value("1 pizza") //"1 pizza"
value([]) //[]
value({}) //{}
value(0) //0
value(1) //1
value(-1) //-1
value(3.14) //3.14
value(0x2) //2
value(1e+99) //1e+99
you get the idea
function value(x){
if(typeof x==="string"){
if(x=="") return x;
if(!isNaN(x)) return Number(x);
if(x=="true") return true;
if(x=="false") return false;
if(x=="null") return null;
if(x=="undefined") return undefined;
}
return x;
}
The major problem is that because isNaN() return "is a Number" for things like
"" empty strings
" " blank strings
[] arrays
etc
Edit
Based on the accepted answer:
function value(x) {
if (typeof x === "string") {
switch (x) {
case "true": return true;
case "false": return false;
case "null": return null;
case "undefined": return void 0;
}
if (!isNaN(x) && !isNaN(parseFloat(x))) return +x;
}
return x;
}