JS | Parse Int
by Zoltan Boros
HTML
<pre id="out"></pre>
JavaScript
var out = document.getElementById("out");
function print(string)
{
out.innerHTML += string + "\n";
}
function parseIntStrictly(value)
{
if (/^(-|\+)?(\d+)$/.test(value)) {
return Number(value);
}
throw "NaN";
}
var items = [
{ value : false, isInt : false },
{ value : true, isInt : false },
{ value : 12, isInt : true },
{ value : -14, isInt : true },
{ value : +15, isInt : true },
{ value : 0, isInt : true },
{ value : 2.3, isInt : false },
{ value : "34", isInt : true },
{ value : "", isInt : false },
{ value : "NaN", isInt : false },
{ value : NaN, isInt : false },
{ value : "a", isInt : false }
];
for (var i in items) {
var value = items[i].value;
var isInt = items[i].isInt;
var valueAsInt, verdict;
try {
valueAsInt = parseIntStrictly(value);
verdict = isInt;
} catch (ex) {
valueAsInt = "n.a.";
verdict = !isInt;
}
print("'" + value + "' (" + typeof value + ") as integer: " + valueAsInt + " (" + (verdict ? "ok" : "NOK") + ")");
}