Two answers for you:
Based on parsing
Regular expression
Note that in both cases, I've interpreted "positive integer" to include 0
, even though 0
is not positive. I include notes if you want to disallow 0
.
Based on Parsing
If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:
function isNormalInteger(str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
or if you want to allow whitespace and leading zeros:
function isNormalInteger(str) {
str = str.trim();
if (!str) {
return false;
}
str = str.replace(/^0+/, "") || "0";
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
Live testbed (without handling leading zeros or whitespace):
function isNormalInteger(str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
function gid(id) {
return document.getElementById(id);
}
function test(str, expect) {
var result = isNormalInteger(str);
console.log(
str + ": " +
(result ? "Yes" : "No") +
(expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
);
}
gid("btn").addEventListener(
"click",
function() {
test(gid("text").value);
},
false
);
test("1", true);
test("1.23", false);
test("1234567890123", true);
test("1234567890123.1", false);
test("0123", false); // false because we don't handle leading 0s
test(" 123 ", false); // false because we don't handle whitespace
<label>
String:
<input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…