Having some trouble trying to validate strings that are numbers in JS. isNaN in particular seems to be misbehaving.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>No Quirks!</title>
</head>
<body>
<h1>JavaScript Test</h1>
<button onclick="myNanIsTrue()">Is it a number?</button>
<p id="writeToHTML"></p>
<script type="text/javascript">
function myNanIsTrue() {
var g = parseInt("40000000") + "<br />";
var n = g;
if (isNaN(g)){
g="moo!";
}
n += g + "<br />";
document.getElementById("writeToHTML").innerHTML = n;
}
</script>
</body>
</html>
Tried a couple of permutations of this but it just doesn't seem to be working. Can anyone see why this isn't working?
You've written:
var g = parseInt("40000000") + "<br />";
Therefore g
is a string: '40000000<br />'
.
parseInt("40000000")
returns an integer, but then you append a string to it. Javascript implicitly converts the numer to a string, then concatenates them.
String's not a number, so isNaN
(correctly) returns true
.